目录
一、使用ServletAPI向request域对象共享数据(不常用)
二、使用ModelAndView向request域对象共享数据
🦆ModuleAndView包含Module和View的功能
- @RequestMapping("/testSession")
- public String testSession(HttpSession session){
- session.setAttribute("testSessionScope", "hello,session");
- return "success";
- }
<a th:href="@{/test/mav}">测试通过ModelAndView向请求域共享数据a>
🦆ModuleAndView包含Module和View的功能
- Module:向请求域中共享数据
- View:设计逻辑视图,实现页面跳转
使用ModuleAndView时,可以使用其Module功能向请求域共享数据
使用View功能设置逻辑视图,但是控制器方法一定要将ModuleAndView作为方法的返回值
- html>
- <html lang="en" xmlns:th="http://www.thymeleaf.org">
- <head>
- <meta charset="UTF-8">
- <title>首页title>
- head>
- <body>
- <h1>success.htmlh1>
- <p th:text="${testRequestScope}">p>
- body>
- html>
- package com.atguigu.controller;
-
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.servlet.ModelAndView;
-
- @Controller
- public class TestScopeController {
- @RequestMapping("/test/mav")
- public ModelAndView testMAV(){
- ModelAndView mav = new ModelAndView();
- //向请求域中共享数据
- mav.addObject("testRequestScope","hello,ModuleAndView");
- //设置逻辑视图
- mav.setViewName("success");
- return mav;
- }
- }

<a th:href="@{/test/model}">测试通过Model向请求域共享数据a>
- @RequestMapping("/test/model")
- public String testModel(Model model){
- model.addAttribute("testRequestScope","hello,Model");
- return "success";
- }
<a th:href="@{/test/map}">测试通过Map向请求域共享数据a><br>
- @RequestMapping("/test/map")
- public String testMap(Map
map) { - map.put("testRequestScope","hello,Map");
- return "success";
- }
<a th:href="@{/test/modelMap}">测试通过ModelMap向请求域共享数据a><br>
- @RequestMapping("/test/modelMap")
- public String testModelMap(ModelMap modelMap){
- modelMap.addAttribute("testRequestScope","hello,ModelMap");
- return "success";
- }
Model、ModelMap、Map类型的形参其实本质上都是 BindingAwareModelMap 创建的
- public interface Model{}
- public class ModelMap extends LinkedHashMap
{} - public class ExtendedModelMap extends ModelMap implements Model {}
- public class BindingAwareModelMap extends ExtendedModelMap {}
只与浏览器是否关闭有关,与服务器是否关闭无关
<a th:href="@{/test/session}">测试向会话域共享数据a><br>
- html>
- <html lang="en" xmlns:th="http://www.thymeleaf.org">
- <head>
- <meta charset="UTF-8">
- <title>首页title>
- head>
- <body>
- <h1>success.htmlh1>
- <p th:text="${testRequestScope}">p>
- <p th:text="${session.testSessionScope}">p>
- <p th:text="${application.testApplicationScope}">p>
- body>
- html>
- @RequestMapping("/test/session")
- public String testSession(HttpSession session){
- session.setAttribute("testSessionScope","hello,session");
- return "success";
- }
<a th:href="@{/test/application}">测试向应用域共享数据a><br>
- @RequestMapping("/test/application")
- public String testApplication(HttpSession session){
- ServletContext servletContext = session.getServletContext();
- servletContext.setAttribute("testSessionScope", "hello,application");
- return "success";
- }
