一、使用ServletAPI向request域共享数据
//TestController
@Controller
public class TestController {
@RequestMapping("/")
public String index(){
return "index";
}
}
//ScopeController.java
@RequestMapping("/testRequestByservletAPI")
public String testRequestByservletAPI(HttpServletRequest request){
request.setAttribute("testRequestScope", "hello,servletAPI");
return "success";
//index.html
<a th:href="@{/testRequestByservletAPI}">通过ServletAPI向request域共享数据</a><br>
//success.html
<p th:text="${testRequestScope}"></p>
二、使用ModelAndView向request域对象共享数据
@RequestMapping("/testModelAndView")
public ModelAndView testModelAndView(){
/**
* ModelAndView有Model和View的功能
* Model主要用于向请求域共享数据
* View主要用于设置视图,实现页面跳转
*/
ModelAndView mav = new ModelAndView();
//向请求域共享数据
mav.addObject("testRequestScope", "hello,ModelAndView");
//设置视图,实现页面跳转
mav.setViewName("success");
return mav;
}
1234567891011121314
<a th:href="@{/testModelAndView}">通过ModelAndView向request域对象共享数据</a><br>
三、使用Model向request域对象共享数据
@RequestMapping("/testModel")
public String testModel(Model model){
model.addAttribute("testRequestScope", "hello,Model");
//设置视图,实现页面跳转
return "success";
}
<a th:href="@{/testModel}">通过Model向request域对象共享数据</a><br>
四、使用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>
五、使用ModelMap向request域对象共享数据
@RequestMapping("/testModelMap")
public String testModelMap(ModelMap modelMap){
modelMap.addAttribute("testRequestScope", "hello,ModelMap");
return "success";
}
<a th:href="@{/testModelMap}">通过ModelMap向request域对象共享数据</a><br>
六、Model、ModelMap、Map的关系
Model、ModelMap、Map类型的参数其实本质上都是 BindingAwareModelMap 类型的
public interface Model{}
public class ModelMap extends LinkedHashMap<String, Object> {}
public class ExtendedModelMap extends ModelMap implements Model {}
public class BindingAwareModelMap extends ExtendedModelMap {}
七、向session域共享数据
@RequestMapping("/testSession")
public String testSession(HttpSession session){
session.setAttribute("testSessionScope", "hello,session");
return "success";
}
<a th:href="@{/testSession}">通过ServletAPI向Session域对象共享数据</a><br>
<p th:text="${session.testSessionScope}"></p>
八、向application域共享数据
@RequestMapping("/testApplication")
public String testApplication(HttpSession session){
ServletContext application = session.getServletContext();
application.setAttribute("testApplicationScope", "hello,application");
return "success";
}
<a th:href="@{/testApplication}">通过ServletAPI向Application域对象共享数据</a><br>
<p th:text="${application.testApplicationScope}"></p>