域对象共享数据
保存作用域 / 域对象:从上到下作用域依次增大
1、PageContext / Page:页面级别,现在已不使用
2、HttpServletRequest / Request:一次请求响应范围有效
3、HttpSession / Session:一次会话范围有效,浏览器开启 -> 浏览器关闭
4、ServletContext / Application:一次应用程序范围有效,服务器开启 -> 服务器关闭
向 Request 域对象共享数据
1、.html 设置
<!-- 引入thymeleaf名称空间 -->
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<!-- 获取value -->
<p th:text="${key}"></p>
2、控制器方法
(1)使用 Servlet API(不使用)
@RequestMapping(value = "/Request")
public String test(HttpServletRequest request) {
    request.setAttribute("key", "value");
    return "target";
}
(2)使用 ModelAndView(建议)
@RequestMapping(value = "/Request")
public ModelAndView test() {
    /**
    * 功能
    * Model向请求域共享数据
    * View设置视图,实现页面跳转
    */
    ModelAndView modelAndView = new ModelAndView();
    //处理模型数据,向请求域request共享数据
    modelAndView.addObject("key","value");
    //设置视图名称,即页面路径
    modelAndView.setViewName("target");
    //返回ModelAndView,令前端控制器解析
    return modelAndView;
}
(3)使用 Model
@RequestMapping(value = "/Request")
public String test(Model model) {
    //处理模型数据,向请求域request共享数据
    model.addAttribute("key", "value");
    //返回视图名称,即页面路径
    return "target";
}
(4)使用 Map
@RequestMapping(value = "/Request")
public String test(Map<String, Object> map) {
    //Map集合的数据,即共享域的数据
    map.put("key", "value");
    //返回视图名称,即页面路径
    return "target";
}
(5)使用 ModelMap
@RequestMapping(value = "/Request")
public String test(ModelMap modelMap) {
    //处理模型数据,向请求域request共享数据
    modelMap.addAttribute("key", "value");
    //返回视图名称,即页面路径
    return "target";
}
3、DispatcherServlet 源码
mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
(1)结论:不论何种方式,都会将模型、视图封装到 ModelAndView
ModelMap、Model、Map
1、本质:org.springframework.validation.support.BindingAwareModelMap
2、关系
public class BindingAwareModelMap extends ExtendedModelMap
public class ExtendedModelMap extends ModelMap implements Model
public interface Model
public class ModelMap extends LinkedHashMap<String, Object>
public class LinkedHashMap<K,V>
    extends HashMap<K,V>
    implements Map<K,V>
使用 Servlet API 向 HttpSession 域共享数据(建议)
1、.html 设置
<!-- 引入thymeleaf名称空间 -->
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<!-- 获取value,session是Thymeleaf内置对象 -->
<p th:text="${session.key}"></p>
2、控制器方法
@RequestMapping(value = "/Session")
public String test(HttpSession session) {
    session.setAttribute("key", "value");
    return "target";
}
使用 Servlet API 向 ServletContext 域共享数据
1、.html 设置
<!-- 引入thymeleaf名称空间 -->
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<!-- 获取value,appliction是Thymeleaf内置对象 -->
<p th:text="${application.key}"></p>
2、控制器方法
(1)方法:getServletContext()
(2)调用对象:HttpServletRequest、HttpSession、ServletConfig
(3)示例
@RequestMapping(value = "/Application")
public String test(HttpSession session) {
    ServletContext servletContext = session.getServletContext();
    servletContext.setAttribute("key","value");
    return "target";
}
                    
                
                
            
        
浙公网安备 33010602011771号