第四章 使用(servletAPI、ModelAndView,Model、Map、ModelMap)向request域对象共享数据,向session,application域中共享数据
1.域对象共享数据:
(1)使用servletAPI向request域对象共享数据:
@Controller
public class TestController {
@RequestMapping("/")
public String index(){
return "index";
}
}
<!--index.html-->
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>首页</title>
</head>
<body>
<h1>首页</h1>
<a th:href="@{/testRequestByServletAPI}">使用servletAPI向request域中共享数据</a>
</body>
</html>
@Controller
public class ScopeController {
//使用servletAPI向request域中共享数据
@RequestMapping("/testRequestByServletAPI")
public String testRequestByServletAPI(HttpServletRequest request){
//共享数据
request.setAttribute("testRequestScope","hello,servletAPI");
return "success";
}
}
<!--success.html-->
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
success<br>
<p th:text="${testRequestScope}"></p>
</body>
</html>
(2)使用ModelAndView向request域对象共享数据:
@RequestMapping("/testModelAndView")
public ModelAndView testModelAndView(){
ModelAndView mav=new ModelAndView();
//处理模型数据,即向请求域request共享数据
mav.addObject("testRequestScope","hello,ModelAndView");
//设置视图名称
mav.setViewName("success");
return mav;
}
<a th:href="@{/testModelAndView}">使用ModelAndView向request域对象共享数据</a><br>
(3)使用Model向request域对象共享数据:
@RequestMapping("/testModel")
public String testModel(Model model){
model.addAttribute("testRequestScope","hello,Model");
return "success";
}
<a th:href="@{/testModel}">使用Model向request域对象共享数据</a><br>
(4)使用map向request域对象共享数据:
@RequestMapping("/testMap")
public String testMap(Map<String,Object> map){
map.put("testRequestScope","hello,Map");
return "success";
}
<a th:href="@{/testMap}">使用Map向request域对象共享数据</a><br>
(5)使用ModelMap向request域对象共享数据:
@RequestMapping("/testModelMap")
public String testModeMap(ModelMap modelMap){
modelMap.addAttribute("testRequestScope","hello,ModelMap");
return "success";
}
<a th:href="@{/testModelMap}">使用ModelMap向request域对象共享数据</a><br>
(6)向session域中共享数据:
@RequestMapping("/testSession")
public String testSession(HttpSession session){
session.setAttribute("testRequestScope","hello,session");
return "success";
}
<a th:href="@{/testSession}">使用testSession向session域对象共享数据</a><br>
<p th:text="${session.testRequestScope}"></p>
(7)向application域中共享数据:
@RequestMapping("/testApplication")
public String testApplication(HttpSession session){
ServletContext application=session.getServletContext();
application.setAttribute("testApplicationScope","hello,application");
return "success";
}
<p th:text="${application.testApplicationScope}"></p>
<a th:href="@{/testApplication}">使用testApplication向application域对象共享数据</a><br>