SpringMVC学习笔记
5.1)向request域对象共享数据
5.1.1)使用ServletAPI向request域对象共享数据
使用ServletAPI向request域对象共享数据,代码如下:
@Controller
public class ScopeController {
//使用servletAPI向request域对象共享数据
@RequestMapping("/testRequestByServletAPI")
public String testRequestByServletAPI(HttpServletRequest request) {
request.setAttribute("testRequestScope", "hello,servletAPI");
return "success";
}
}
首页 index.html,代码如下:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>首页</h1>
<a th:href="@{/testRequestByServletAPI}">通过servletAPI向request域对象共享数据</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>
success<br>
<p th:text="${testRequestScope}"></p>
</body>
</html>
【配置Tomacat后启动工程,浏览器访问:http://localhost:8080/SpringMvcDemo3/】,点击超链接“通过servletAPI向request域对象共享数据”,页面跳转至:http://localhost:8080/SpringMvcDemo3/testRequestByServletAPI,页面如下:
5.1.2)使用ModelAndView向request域对象共享数据
使用ModelAndView向request域对象共享数据,代码如下:
// 使用ModelAndView向request域对象共享数据
@RequestMapping("/testModelAndView")
public ModelAndView testModelAndView() {
ModelAndView mav = new ModelAndView();
//处理模型数据,即向请求域request共享数据
mav.