SpringMVC学习笔记(六)
SpringMVC提供了几种种途径来处理带数据的视图,分别是:ModelAndView、Map、ModelMap及Model,@SessionAtrributes,@ModelAttribute。下面我们分别来具体介绍:
1.使用ModelAndView处理数据
请求页面:
<a href="model/testModelAndView">超链接测试1:testModelAndView</a><br/>
控制器controller:
//使用ModelAndView类型的参数
@RequestMapping(value="/testModelAndView")
public ModelAndView testModelAndView() {
String view="modelSuccess";
ModelAndView m=new ModelAndView(view);
Student student=new Student();
student.setsName("张小蟀1");
//添加student对象数据放入ModelAndView中
m.addObject("student",student);
return m;
}
响应页面:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>成功界面</title>
</head>
<body>
request作用域中:${requestScope.student.sName}<br/>
session作用域中:${sessionScope.student.sName}
</body>
</html>
运行结果:
ModelAndView的构造方法将视图页面的名称modelSuccess放入定义的m对象中,在通过addOBbject()方法将输入放入m对象,最后返回mv,程序会吧m中的数据student放入request作用域中。
2.使用Map、ModelMap、Model作为方法来处理数据
请求页面:
<a href="model/testMap">超链接测试2:testMap</a><br/>
<a href="model/testModelMap">超链接测试3:testModelMap</a><br/>
<a href="model/testModel">超链接测试4:testModel</a><br/>
控制器controller:
//使用Map类型的参数
@RequestMapping(value="/testMap")
public String testMap(Map<String,Object> map) {
Student student=new Student();
student.setsName("张小蟀2");
map.put("student", student);
return "modelSuccess";
}
//使用ModelMap类型的参数
@RequestMapping(value="/testModelMap")
public String testModelMap(ModelMap map) {
Student student=new Student();
student.setsName("张小蟀3");
map.put("student", student);
return "modelSuccess";
}
//使用Model类型的参数
@RequestMapping(value="/testModel")
public String testModel(Model map) {
Student student=new Student();
student.setsName("张小蟀4");
map.addAttribute("student", student);
return "modelSuccess";
}
请求页面还是和上面ModelAndView的一样:
运行结果:
给SpringMVC的请求方法增加一个Map、ModelMap、Model类型的参数,向Map、ModelMap、Model中增加数据,该数据也会放入request作用域中。