1.Request域--傳統使用方式
@RequestMapping("/test01.action")
public String test01(HttpServletRequest request){
request.setAttribute("k1","v1");
request.setAttribute("k2","v2");
return "my01test01";
}
前端獲取值
EL表達式中寫了requestScope那麼就是從request域中去取值,也可以不指定,那麼系統會按照默認的去找
<body>
request:${requestScope.k1}<br/>
request:${requestScope.k2}<br/>
</body>
測試結果:
2.Request域 - SpringMVC方式
在SpringMVC中向Modle中存放的數據本質上就是存入了Request域中
向model中存放的數據就是存在request域,所以request域的寫法可以換成model來存值
@RequestMapping("/test02.action")
public String test02(Model model){
model.addAttribute("k1","v1");
model.addAttribute("k2","v2");
return "my01test02";
}
前端獲取值
<body>
this is my01test02.jsp...<br/>
request:${requestScope.k1}<br/>
request:${requestScope.k2}<br/>
</body>
測試結果
3. Session域 - 傳統方式
@RequestMapping("/test03.action")
public String test03(HttpSession session){
session.setAttribute("sk1","sv1");
session.setAttribute("sk2","sv2");
return "my01test03";
}
前端獲取值
<body>
this is my01test03.jsp...<br/>
session:${sessionScope.sk1}<br/>
session:${sessionScope.sk2}<br/>
</body>
測試結果
4.Session域 - SpringMVC方式
在類上標註@SessionAttributes,則這個控制器類內部的所有控制器方法,向model中存入指定鍵值對,除了會存入request域之外,還會複製一份到session域中,@SessionAttributes作用於整個類,所以類中所有方法存值都會存一份到session,使用時需要注意(此註解只能用在類上,不能單獨用在方法上,類中方法數據需要單獨處理的話,採用傳統的session存值方式)
@RequestMapping("/test04.action")
public String test04(Model model){
model.addAttribute("sk1","sv1");
model.addAttribute("sk2","sv2");
return "my01test04";
}
前端代碼
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>my01test04.jsp</title>
</head>
<body>
this is my01test04.jsp...<br/>
request:${requestScope.sk1}<br/>
request:${requestScope.sk2}<br/>
session:${sessionScope.sk1}<br/>
session:${sessionScope.sk2}<br/>
</body>
</html>
測試結果:
5.ServletContext域 - 傳統方式
SpringMVC並沒有提供,所以沒有便捷方法,只能通過傳統方式進行操作
@RequestMapping("/test05.action")
public String test05(HttpServletRequest request){
ServletContext sc = request.getServletContext();
sc.setAttribute("sck1","scv1");
sc.setAttribute("sck2","scv2");
return "my01test05";
}
前端代碼
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>my01test05.jsp</title>
</head>
<body>
this is my01test05.jsp...<br/>
ServletContext:${applicationScope.sck1}<br/>
ServletContext:${applicationScope.sck2}<br/>
</body>
</html>
測試結果:
6.pageContext
此處不涉及該域