处理请求的过程:
获取请求参数,调用service处理业务逻辑, 往域对象中共享数据,最后实现渲染页面跳转。
请求域中共享数据
ModelAndView向request域对象共享数据
ModelAndView:往域对象共享数据,并实现页面跳转和渲染页面。
- 使用ModelAndView时,可以使用其Model功能向请求域共享数据。
- 使用View功能设置逻辑视图实现页面跳转,但是控制器方法的返回值一定要
将ModelAndView作为方法的返回值。
index.html
<a th:href="@{/test/mav}">测试通过ModelandView向请求域共享数据</a>
controller
@RequestMapping("/test/mav")
// 如果要用ModelAndView,必须将ModelAndView进行返回
public ModelAndView testMAV(){
ModelAndView mav=new ModelAndView();
// 向请求域中共享数据
mav.addObject("testRequestScope","hello,ModelAndView");
mav.setViewName("success");
return mav;
}
success.html
<p th:text="${application.testApplicationScope}"></p>
Model向request域对象共享数据
DispatcherServlet调用方法的时候直接创建这个Model对象。
<a th:href="@{/test/model}">测试通过Model向请求域共享数据</a><br>
@RequestMapping("/test/model")
// 方法的返回值是String,现在用的是ModelAndView里面的Model功能
public String testModel(Model model){
model.addAttribute("testRequestScope","hello,Model");
return "success";
}
ModelMap向request域对象共享数据
跟Model的向request域对象共享数据一样。
Map向request域对象共享数据
@RequestMapping("/test/map")
// 方法的返回值是String,现在用的是ModelAndView里面的Model功能
public String testModel(Map<String,Object > map){ //直接创建model对象
map.put("testRequestScope","hello,map");
return "success";
}
注:这三种类型都是:org.springframework.validation.support.BindingAwareModelMap类型
ServletAPI向request域对象共享数据
@RequestMapping("/testServletAPI")
public String testServletAPI(HttpServletRequest request){
request.setAttribute("testScope", "hello,servletAPI");
return "success";
}
会话域和应用域共享数据
直接使用servletAPI,相比较而言,springmvc提供的方式并没有使用servletAPI简单。
<a th:href="@{/test/session}">测试向会话域共享数据</a><br>
<a th:href="@{/test/application}">测试通过应用域共享数据</a><br>
@RequestMapping("/test/session")
public String testSession(HttpSession session){
session.setAttribute("testSessionScope","hello,session");
return "success";
}
@RequestMapping("/test/application")
public String testApplication(HttpSession session){
ServletContext servletContext = session.getServletContext();
servletContext.setAttribute("testApplicationScope","hello,application");
return "success";
}
<h1>success.html</h1>
<p th:text="${session.testSessionScope}"></p>
<p th:text="${application.testApplicationScope}"></p>