SpringMVC之域对象共享数据的多种方式
  RbYwdB2s8Ab9 2024年02月19日 126 0

本次场景演示使用Thymeleaf服务器渲染技术。

使用Servlet向域中共享数据

@GetMapping("/testServletScope")
public String testServlet(HttpServletRequest request) {
     request.setAttribute("testRequestScope", "hello,servlet");
     return "success";
}

使用ModelAndView向域中共享数据

@GetMapping("/testModelAndView")
public ModelAndView testModelAndView() {
	ModelAndView modelAndView = new ModelAndView();
	modelAndView.addObject("testRequestScope", "hello,ModelAndView");
	modelAndView.setViewName("success");
	return modelAndView;
}

使用Model向域中共享数据

@GetMapping("/testModel")
public String testModel(Model model) {
	model.addAttribute("testRequestScope", "hello,Model");
	return "success";
}

使用Map集合向域中共享数据

@GetMapping("/testMap")
public String testMap(Map<String, Object> map) {
	map.put("testRequestScope","hello,Map");
	return "success";
}

使用ModelMap向域中共享数据

@GetMapping("/testModelMap")
public String testModelMap(ModelMap modelMap) {
	modelMap.addAttribute("testRequestScope","hello,ModelMap");
	return "success";
}

使用session向域中共享数据

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

使用ServletContext向域中共享数据

@GetMapping("/testApplication")
public String testApplication(HttpSession session) {
	ServletContext application = session.getServletContext();
	application.setAttribute("testApplicationScope","hello,Application");
	return "success";
}

测试

创建testScope.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>测试域对象</title>
</head>
    <body>
        <a th:href="@{/testServletScope}">测试通过Servlet向域中共享数据</a><br/>
        <a th:href="@{/testModelAndView}">测试通过ModelAndView向域中共享数据</a><br/>
        <a th:href="@{/testModel}">测试通过Model向域中共享数据</a><br/>
        <a th:href="@{/testMap}">测试通过Map集合向域中共享数据</a><br/>
        <a th:href="@{/testModelMap}">测试通过ModelMap向域中共享数据</a><br/>
        <a th:href="@{/testSession}">测试向Session域中共享数据</a><br/>
        <a th:href="@{/testApplication}">测试向Application域中共享数据</a><br/>
    </body>
</html>

创建success.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h2>SUCCESS...</h2>
<p th:text="${testRequestScope}"></p>
<p th:text="${session.testSessionScope}"></p>
<p th:text="${application.testApplication}"></p>
</body>
</html>

请求页面跳转

@GetMapping("/testScope")
public String testScope() {
    return "testScope";
}
【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2024年02月19日 0

暂无评论

推荐阅读
  2Vtxr3XfwhHq   2024年05月17日   53   0   0 Java
  Tnh5bgG19sRf   2024年05月20日   109   0   0 Java
  8s1LUHPryisj   2024年05月17日   46   0   0 Java
  aRSRdgycpgWt   2024年05月17日   47   0   0 Java
RbYwdB2s8Ab9