SpringMVC 域对象共享数据

文章目录

1、使用ServletAPI向request域对象共享数据

java 复制代码
@RequestMapping("/testServletAPI")
public String testServletAPI(HttpServletRequest request){
    request.setAttribute("testScope", "hello,servletAPI");
    return "success";
}

2、使用ModelAndView向request域对象共享数据

java 复制代码
@RequestMapping("/testModelAndView")
public ModelAndView testModelAndView(){
    /**
     * ModelAndView有Model和View的功能
     * Model主要用于向请求域共享数据
     * View主要用于设置视图,实现页面跳转
     */
    ModelAndView mav = new ModelAndView();
    //向请求域共享数据
    mav.addObject("testScope", "hello,ModelAndView");
    //设置视图,实现页面跳转
    mav.setViewName("success");
    return mav;
}

3、使用Model向request域对象共享数据

java 复制代码
@RequestMapping("/testModel")
public String testModel(Model model){
    model.addAttribute("testScope", "hello,Model");
    return "success";
}

4、使用map向request域对象共享数据

java 复制代码
@RequestMapping("/testMap")
public String testMap(Map<String, Object> map){
    map.put("testScope", "hello,Map");
    return "success";
}

5、使用ModelMap向request域对象共享数据

java 复制代码
@RequestMapping("/testModelMap")
public String testModelMap(ModelMap modelMap){
    modelMap.addAttribute("testScope", "hello,ModelMap");
    return "success";
}

6、Model、ModelMap、Map的关系

Model、ModelMap、Map类型的参数其实本质上都是 BindingAwareModelMap 类型的

复制代码
public interface Model{}
public class ModelMap extends LinkedHashMap<String, Object> {}
public class ExtendedModelMap extends ModelMap implements Model {}
public class BindingAwareModelMap extends ExtendedModelMap {}

7、向session域共享数据

java 复制代码
@RequestMapping("/testSession")
public String testSession(HttpSession session){
    session.setAttribute("testSessionScope", "hello,session");
    return "success";
}

8、向application域共享数据

java 复制代码
@RequestMapping("/testApplication")
public String testApplication(HttpSession session){
	ServletContext application = session.getServletContext();
    application.setAttribute("testApplicationScope", "hello,application");
    return "success";
}
相关推荐
心中有你02147 小时前
【路径规划】A*寻路算法最通俗易懂讲解(C语言完整实现+详细注释)
c语言·开发语言·算法
言乐68 小时前
Python自动去除水印
开发语言·python·django·virtualenv·pygame
大圣编蚕8 小时前
C语言入门:基本语法汇总
c语言·开发语言
czq_26867194878 小时前
Python打卡第31天
开发语言·python
invicinble8 小时前
python 编程语言 认识维度
开发语言·数据库·python
AC赳赳老秦8 小时前
数据采集全链路审计留痕:用 OpenClaw 实现合规审计与追溯
开发语言·汇编·python·php·swift·deepseek·openclaw
czhc11400756638 小时前
退出防呆:用“总闸“收口所有退出入口,以及三个并发语法坑
开发语言·c#
三8448 小时前
Fastjson 漏洞 · 02 · autoType 机制与 checkAutoType
java·fastjson
悠仁さん8 小时前
【C++】vector 类
开发语言·c++