1.使用ServletAPI向request域对象共享数据
@Controller public class ScopeController { @RequestMapping("/testServletAPI") public String testServletAPI(HttpServletRequest request) { request.setAttribute("testScope", "hello,servletAPI"); return "success"; // success页面会显示hello,servletAPI } }
// success.html <body> <p th:text="${testScope}"></p> <p th:text="${session.testSessionScope}"></p> <p th:text="${application.testApplicationScope}"></p> </body> // index.html <body> <a th:href="@{/testServletAPI}">通过ServletAPI向request域对象共享数据</a> <a th:href="@{/testModelAndView}">通过ModelAndView向request域对象共享数据</a> <a th:href="@{/testModel}">通过Model向request域对象共享数据</a> <a th:href="@{/testMap}">通过Map向request域对象共享数据</a> <a th:href="@{/testSession}">通过ServletAPI向Session域对象共享数据</a> <a th:href="@{/testApplication}">通过ServletAPI向Application域对象共享数据</a> </body>
2.使用ModelAndView向request域对象共享数据***
@RequestMapping("/testModelAndView") public ModelAndView testModelAndView(){ /** * ModelAndView有Model和View的功能 * Model主要用于向请求域共享数据 * View主要用于设置视图,实现页面跳转 */ ModelAndView mav = new ModelAndView(); //向请求域共享数据 mav.addObject("testScope", "hello,ModelAndView"); //设置视图,实现页面跳转 mav.setViewName("success"); return mav; // 返回给前端控制器进行解析 }
tips:
- 使用请求request域对象的六种方法时,前端控制器都会使用成一个
ModelAndView
对象把需要跳转的页面(即view)和共享数据(即model)进行封装:// DispatcherServlet.java中的535行 mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
3.使用Model向request域对象共享数据
@RequestMapping("/testModel") public String testModel(Model model){ model.addAttribute("testScope", "hello,Model"); return "success"; }
4.使用map向request域对象共享数据
@RequestMapping("/testMap") public String testMap(Map<String, Object> map){ map.put("testScope", "hello,Map"); return "success"; }
5.使用ModelMap向request域对象共享数据
@RequestMapping("/testModelMap") public String testModelMap(ModelMap modelMap){ modelMap.addAttribute("testScope", "hello,ModelMap"); return "success"; }
6.Model、ModelMap、Map的关系
- 通过
System.out.println(map/model/modelMap.getClass().getName());
会打印org.springframework.validation.support.BindingAwareModelMap
7.向session域共享数据
@RequestMapping("/testSession") public String testSession(HttpSession session){ session.setAttribute("testSessionScope", "hello,session"); return "success"; }
8.向application域共享数据
@RequestMapping("/testApplication") public String testApplication(HttpSession session){ ServletContext application = session.getServletContext(); application.setAttribute("testApplicationScope", "hello,application"); return "success"; }