1. 程式人生 > >SpringMVC(四)資料模型和@SessionAttributes註解

SpringMVC(四)資料模型和@SessionAttributes註解

ModelAndView

//測試處理模型資料ModelAndView
@RequestMapping("testModelAndView")
public ModelAndView testModelAndView(){
	ModelAndView modelAndView = new ModelAndView("success");
	modelAndView.addObject("time",new Date());
	return modelAndView;
}

請求路徑:

<a href="testModelAndView">testModelAndView</a>

成功跳轉頁面如下:

<%@ 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=UTF-8">
<title>Insert title here</title>
</head>
<body>
	success!!!
	<br/>
	time:${requestScope.time }
</body>
</html>

頁面輸出如下:

time:Sun Oct 02 22:28:25 CST 2016

Map

<span style="font-size:14px;">//測試處理模型資料Map
@RequestMapping("testMap")
public String testMap(Map<String,Object> map){
	map.put("names", Arrays.asList("kaka","sheva","Inzaghi"));
	return "success";
}</span>

請求路徑:

<a href="testMap">testMap</a>


成功跳轉頁面如下:

<%@ 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=UTF-8">
<title>Insert title here</title>
</head>
<body>
	success!!!
	<br/>
	names:${requestScope.names }
</body>
</html>

頁面輸出如下:

names:[kaka, sheva, Inzaghi]


@SessionAttributes註解

headler類

<span style="font-size:12px;"><span style="color:#ff0000;">@SessionAttributes(value = {"player"},types={String.class})</span>
@Controller
public class TestPojo {

	//測試SessionAttributes註解用法
	@RequestMapping("testSessionAttributes")
	public String testSessionAttributes(Map<String,Object> map){
		Player p = new Player();
		p.setName("kaka");
		p.setAge(22);
		map.put("player", p);
		map.put("team", "milan");
		return "success";
	}
}
</span>

請求路徑:

<a href="testSessionAttributes">testSessionAttributes</a>

跳轉的jsp頁面:

<%@ 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=UTF-8">
<title>Insert title here</title>
</head>
<body>
	success!!!
	<br/>
	request player:${requestScope.player }
	<br/>
	session player:${sessionScope.player }
	<br/>
	request team:${requestScope.team }
	<br/>
	session team:${sessionScope.team }
</body>
</html>

頁面輸出結果:

request player:Player [name=kaka, age=22, team=null]
session player:Player [name=kaka, age=22, team=null]
request team:milan
session team:milan