展开
拓展 关闭
订阅号推广码
GitHub
视频
公告栏 关闭

Spring MVC入门(四):域对象共享数据

  • 使用ServletAPI向request域对象共享数据
# 后端:向request域对象中添加数据,并转发到success页面
@RequestMapping("/testServletAPI")
public String testServletAPI(HttpServletRequest request){
    request.setAttribute("testScope", "hello,servletAPI");
    return "success";
}

# thymeleaf编写的success页面中获取数据
<p th:text="${testScope}"></p>

# 浏览器访问如下
http://localhost:8080/上下文路径/testServletAPI
  • 使用ModelAndView向request域对象共享数据
# 后端:创建ModelAndView对象,并将对象返回给前端控制器,前端控制器解析对象
@RequestMapping("/testModelAndView")
public ModelAndView testModelAndView(){
    /**
    * ModelAndView有Model和View的功能
    * Model主要用于向请求域共享数据
    * View主要用于设置视图,实现页面跳转
    */
    ModelAndView mav = new ModelAndView();
    //向请求域共享数据
    mav.addObject("testScope", "hello,ModelAndView");
    //设置视图,实现页面跳转
    mav.setViewName("success");
    return mav;
}

# thymeleaf编写的success页面中获取数据
<p th:text="${testScope}"></p>

# 浏览器访问如下
http://localhost:8080/上下文路径/testModelAndView
  • 使用Model向request域对象共享数据
@RequestMapping("/testModel")
public String testModel(Model model){
    model.addAttribute("testScope", "hello,Model");
    return "success";
}

# thymeleaf编写的success页面中获取数据
<p th:text="${testScope}"></p>

# 浏览器访问如下
http://localhost:8080/上下文路径/testModel
  • 使用map向request域对象共享数据
@RequestMapping("/testMap")
public String testMap(Map<String, Object> map){
    map.put("testScope", "hello,Map");
    return "success";
}

# thymeleaf编写的success页面中获取数据
<p th:text="${testScope}"></p>

# 浏览器访问如下
http://localhost:8080/上下文路径/testMap
  • 使用ModelMap向request域对象共享数据
@RequestMapping("/testModelMap")
public String testModelMap(ModelMap modelMap){
    modelMap.addAttribute("testScope", "hello,ModelMap");
    return "success";
}

# thymeleaf编写的success页面中获取数据
<p th:text="${testScope}"></p>

# 浏览器访问如下
http://localhost:8080/上下文路径/testModelMap
  • Model、ModelMap、Map类型的参数其实本质上都是 BindingAwareModelMap 类型的

  • 向session域共享数据

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

# thymeleaf编写的success页面中获取数据
<p th:text="${session.testSessionScope}"></p>

# 浏览器访问如下
http://localhost:8080/上下文路径/testSession
  • 向application域共享数据
@RequestMapping("/testApplication")
public String testApplication(HttpSession session){
    ServletContext application = session.getServletContext();
    application.setAttribute("testApplicationScope", "hello,application");
    return "success";
}

# thymeleaf编写的success页面中获取数据
<p th:text="${application.testApplicationScope}"></p>

# 浏览器访问如下
http://localhost:8080/上下文路径/testApplication
posted @ 2022-04-21 20:43  DogLeftover  阅读(19)  评论(0编辑  收藏  举报