开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第27天,点击查看活动详情
三种域对象
Request:一次请求
Session:一次会话。从浏览器开启到浏览器关闭(只跟浏览器是否关闭有关,与服务器是否关闭无关)
-
- 钝化:浏览器未关闭而服务器关闭,
Session数据序列化到磁盘上
- 钝化:浏览器未关闭而服务器关闭,
-
- 活化:浏览器仍然关闭而服务器开启,将钝化内容读取到
Session中
- 活化:浏览器仍然关闭而服务器开启,将钝化内容读取到
Application/Servlet Context:上下文对象,整个应用范围。服务器开启时创建,服务器关闭时销毁,从头到尾只创建一次(只跟服务器是否关闭有关,与浏览器是否关闭无关)
选择域对象时,应该选择能实现功能、范围最小的域对象
向 request 域对象共享数据
通过 Servlet API
@RequestMapping("/testRequestByServletAPI")
public String testRequestByServletAPI(HttpServletRequest request) {
request.setAttribute("testRequestScope", "hello, Servlet API!");
return "successrequest";
}
使用Model
我们可以使用Model来往域中存数据。然后使用之前的方式实现页面跳转。
例如
我们要求访问 /testRequestScope 这个路径时能往Request域中存name和title数据,然后跳转到 /WEB-INF/page/testScope.jsp 这个页面。在Jsp中获取域中的数据。
则可以使用如下写法:
@Controller
public class JspController {
@RequestMapping("/testRquestScope")
public String testRquestScope(Model model){
//往请求域存数据
model.addAttribute("name","三更");
model.addAttribute("title","不知名Java教程UP主");
return "testScope";
}
}
使用ModelAndView
我们可以使用ModelAndView来往域中存数据和页面跳转。
例如
我们要求访问 /testRequestScope2 这个路径时能往域中存name和title数据,然后跳转到 /WEB-INF/page/testScope.jsp 这个页面。在Jsp中获取域中的数据。
则可以使用如下写法:
@Controller
public class JspController {
@RequestMapping("/testRquestScope2")
public ModelAndView testRquestScope2(ModelAndView modelAndView){
//往域中添加数据
modelAndView.addObject("name","三更");
modelAndView.addObject("title","不知名Java教程UP主");
//页面跳转
modelAndView.setViewName("testScope");
return modelAndView;
}
}
注意要把modelAndView对象作为方法的返回值返回。
往Session域存数据并跳转
我们可以使用 @SessionAttributes注解来进行标识,用里面的属性来标识哪些数据要存入Session域。
例如
我们要求访问 /testSessionScope 这个路径时能往域中存name和title数据,然后跳转到 /WEB-INF/page/testScope.jsp 这个页面。在jsp中获取Session域中的数据。
则可以使用如下写法
@Controller
@SessionAttributes({"name"})//表示name这个数据也要存储一份到session域中
public class JspController {
@RequestMapping("/testSessionScope")
public String testSessionScope(Model model){
model.addAttribute("name","三更");
model.addAttribute("title","不知名Java教程UP主");
return "testScope";
}
}
获取Session域中数据
我们可以使用 @SessionAttribute把他加在方法参数上,可以让SpringMVC帮我们从Session域中获取相关数据。
例如:
@Controller
@SessionAttributes({"name"})
public class JspController {
@RequestMapping("/testGetSessionAttr")
public String testGetSessionAttr(@SessionAttribute("name") String name){
System.out.println(name);
return "testScope";
}
}
向 application 域共享数据
形式与HttpSession方式类似,只不过需要先从session对象中获取ServletContext上下文对象,即application域对象,再做操作
后台测试代码
@RequestMapping("/testApplication")
public String testApplication(HttpSession session) {
ServletContext application = session.getServletContext();
application.setAttribute("testApplicationScope", "hello, application!");
return "successapplication";
}
总结
域对象有三种:request(请求域)、session(会话域)和application(上下文)
向request域对象共享数据方式:本质都是ModelAndView
Servlet API(不推荐):HttpServletRequest
ModelAndView:需要返回自身
-
Model、Map、ModelMap:本质都是BindingAwareModelMap
向session域共享数据:HttpSession
向application域共享数据:ServletContext