pageContext:表示的是jsp页面的范围
HttpServletRequest:表示的是一次请求的范围
HttpSession:表示的是一次会话的范围
ServletContext:表示的是整个应用的范围
一、向请求域中共享数据:
1.1使用ServletAPI向request域对象共享数据
@RequestMapping("testServletAPI")
public String testServletAPI(HttpServletRequest request){
request.setAttribute("testScope","hello,servletAPI");
return "success";
}
1.2使用ModelAndView向request域对象共享数据
package com.rgf.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; @Controller public class TestScopeController { @RequestMapping("test/mav") public ModelAndView testMav(){ /** * ModelAndView包含Model和View的功能 * Model主要用于向请求域共享数据 * View主要用于设置逻辑视图,实现页面跳转 */ ModelAndView mav = new ModelAndView(); //向请求域共享数据 mav.addObject("testRequestScope","Hello,ModelAndView"); //设置逻辑视图,实现页面跳转 mav.setViewName("success"); return mav; } }
我们设置在跳转页面进行获取数据:
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>首页</title> </head> <body> <h1>success.html</h1> <p th:text="${testRequestScope}"></p> </body> </html>
同时我们在首页中输入如下所示:
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>首页</title> </head> <body> <h1>index.html</h1> <a th:href="@{/hello}">测试@RequestMapping注解所标识的位置</a><br> <a th:href="@{/abc}">测试@RequestMapping注解的value属性</a> <form th:action="@{/hello}" method="post"> <input type="submit" value="测试@RequestMapping注解的method属性"> </form> <a th:href="@{/hello?username=admin}">测试@RequestMapping注解的params属性(第一种)</a><br> <a th:href="@{/hello(username='admin')}">测试@RequestMapping注解的params属性(第二种)</a><br> <a th:href="@{/aaa/test/ant(username='admin')}">测试@RequestMapping注解支持ant风格的路径</a><br> <br> <form th:action="@{/param/servletAPI}" method="post"> 用户名: <input type="text" name="username"><br> 密码: <input type="password" name="password"><br> 提交: <input type="submit" value="登录"><br> </form> <a th:href="@{/param/servletAPI}"></a> <hr> <a th:href="@{/test/mav}">测试通过ModelAndView向请求域共享数据</a> </body> </html>
我们进行运行:
我们点击ModelAndView的链接,跳转之后,如下所示:
success.html
Hello,ModelAndView
1.3使用Model向请求域共享数据
我们进行如下操作:
@RequestMapping("/test/model") public String testModel(Model model){ model.addAttribute("testRequestScope","hello,Model"); return "success"; }
我们的返回success界面:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>首页</title> </head> <body> <h1>success.html</h1> <p th:text="${testRequestScope}"></p> </body> </html>
我们的首页如下所示:
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>首页</title> </head> <body> <h1>index.html</h1> <a th:href="@{/hello}">测试@RequestMapping注解所标识的位置</a><br> <a th:href="@{/abc}">测试@RequestMapping注解的value属性</a> <form th:action="@{/hello}" method="