在Spring MVC 中处理数据模型的相关知识

1.ModelAndView

/*
* 目标方法的返回值可以是ModelAndView类型
* 其中可以包含视图和模型信息
* SpringMVC 会把ModelAndView的model中数据放入到 request 域当中
*/

@RequestMapping("/testModelAndView")
	public ModelAndView testModelAndView() {
		String viewname = SUCCESS;
		ModelAndView modelAndView = new ModelAndView(viewname);
		//添加模型数据到ModelAndView中
		modelAndView.addObject("time", new Date());
		return modelAndView;
	}

在最后的跳转页面中使用time:${requestScope.time}即可输出!

<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
	<h4>Success Page</h4>
	
	time:${requestScope.time}
	<br><br>	

</body>
</html>

输出如图:
在这里插入图片描述

2.Map及Model

/*
* 目标方法可以添加Map类型(实际上也可以是Model或者ModelMap类型)的参数
*/

@RequestMapping("/testMap")
	public String testMap(Map<String,Object> map) {
		System.out.println(map.getClass().getName());
		map.put("names", Arrays.asList("tom","jerry","mike"));
		return SUCCESS;
	}

在这里插入图片描述
最后的跳转页面:

<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
	<h4>Success Page</h4>
	
	time:${requestScope.time}
	<br><br>
	names:${requestScope.names}
	<br><br>
		
</body>
</html>

输出如图:
在这里插入图片描述

3.@SessionAttributes

/*
 * @SessionAttributes 除了可以通过属性名指定需要放到会话层中的属性外
 * (实际上使用的是value属性值)
 * 还可以通过模型属性的对象类型指定哪些模型属性需要放到会话中
 * (实际上使用的是types属性值)
 * 特别注意:该注解只能放在类的上面!而不能放在方法的上面!
 */
@SessionAttributes(value={"user"},types= {String.class})
@RequestMapping("/springmvc")
@Controller
public class SpringMVCTest {	
	private static final String SUCCESS = "success";
	
	@RequestMapping("/testSessionAttributes")
	public String testSessionAttributes(Map<String,Object> map) {
		User user = new User("TOM", "1234", "[email protected]", 16);
		map.put("user", user);
		map.put("school","atguigu");
		return SUCCESS;
	}
}	

最后的跳转页面:

<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
	<h4>Success Page</h4>
	
	time:${requestScope.time}
	<br><br>
	names:${requestScope.names}
	<br><br>
	request user:${requestScope.user}
	<br><br>
	session user:${sessionScope.user}
	<br><br>
	request school:${requestScope.school}
	<br><br>
	session school:${sessionScope.school}
	<br><br>
</body>
</html>

输出如图:
在这里插入图片描述
相关在这里插入图片描述

发布了11 篇原创文章 · 获赞 0 · 访问量 104

猜你喜欢

转载自blog.csdn.net/qq_43395576/article/details/104468242