Spring MVC通过以下几种途径运输出模型数据:
1.ModelAndView
2.Map及Model
3.@SessionAttributes :会把数据放入session中,该注解只能用在类上。
4.@ModelAttribute
1.ModelAndView
处理方法viewName标识了返回目标页面,通过addObject方法添加模型数据。框架会把model中的数据放入request域对象中。
@RequestMapping("/testModelAndView")
public ModelAndView testModelAndView(){
String viewName=SUCCESS;
ModelAndView mav=new ModelAndView(viewName);
//添加模型数据
mav.addObject("time", new Date());
return mav;
}
在目标页面打印出模型数据
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h3>Success page</h3>
time: ${requestScope.time }
</body>
</html>
2.通过Map及Model
@RequestMapping("/testMap")
public String testMap(Map<String,Object> map){
map.put("names", Arrays.asList("tom","Jerry"));
return SUCCESS;
}
目标页面
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h3>Success page</h3>
time: ${requestScope.time }
<br>
names:${requestScope.names }
</body>
</html>
3.@SessionAttributes注解
这个注解需要使用在类上方,value对应的模型,是方法参数中map的key。该例子中,User会在SessionScope和RequestScope中存在。
@SessionAttributes(value={"user"}) //这里的user是map的key
@RequestMapping("/springmvc")
@Controller
public class SpringMVCTest {
private static final String SUCCESS="success";
@RequestMapping("/testSession")
public String testSessionAttributes(Map<String ,Object> map){
User user=new User("Tom","123231");
map.put("user", user);
return SUCCESS;
}}