@RequestMapping("/test01.action")
public String test01(HttpServletRequest request){
request.setAttribute("k1","v1");
request.setAttribute("k2","v2");
return "my01test01";
}
前端获取值
EL表达式中写了requestScope那么就是从request域中去取值,也可以不指定,那么系统会按照默认的去找
request:${requestScope.k1}
request:${requestScope.k2}
测试结果:
在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";
}
前端获取值
this is my01test02.jsp...
request:${requestScope.k1}
request:${requestScope.k2}
测试结果
@RequestMapping("/test03.action")
public String test03(HttpSession session){
session.setAttribute("sk1","sv1");
session.setAttribute("sk2","sv2");
return "my01test03";
}
前端获取值
this is my01test03.jsp...
session:${sessionScope.sk1}
session:${sessionScope.sk2}
测试结果
在类上标注@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" %>
my01test04.jsp
this is my01test04.jsp...
request:${requestScope.sk1}
request:${requestScope.sk2}
session:${sessionScope.sk1}
session:${sessionScope.sk2}
测试结果:
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" %>
my01test05.jsp
this is my01test05.jsp...
ServletContext:${applicationScope.sck1}
ServletContext:${applicationScope.sck2}
测试结果:
此处不涉及该域