域对象共享数据
1.使用ServletAPI向request域对象共享数据
1 index页:<a th:href="@{/testRequestByServletAPI}">测试使用ServletAPI向request域对象共享数据</a><br>
2 success页:<a th:text="${testRequestScope}"
//使用ServletAPI向request域对象共享数据
@RequestMapping("testRequestByServletAPI")
public String testRequestByServletAPI(HttpServletRequest request) {
//使用setAttribute方法设置
request.setAttribute("testRequestScope", "hello,servletAPI");
return "success";
}
2.使用ModelAndView向request域对象共享数据
1 index页:<a th:href="@{/testModelAndView}">测试使用ModelAndView向request域对象共享数据</a><br>
2 success页:<a th:text="${testRequestScope}"
@RequestMapping("/testModelAndView")
public ModelAndView testModelAndView() {
ModelAndView mv = new ModelAndView();
//使用addObject方法向请求域共享数据
mv.addObject("testRequestScope", "hello,ModelAndView");
//使用setViewName设置视图,实现页面跳转
mav.setViewName("success");
return mv;
}
ModelAndView有Model和View的功能
Model主要用于向请求域共享数据
View主要用于设置视图,实现页面跳转
3.使用Model向request域对象共享数据
index页: <a th:href="@{/testModel}">测试使用Model向request域对象共享数据</a><br>
success页:<a th:text="${testRequestScope}"
@RequestMapping("/testModel")
public String testModel(Model model){
//使用addAttribute方法
model.addAttribute("testRequestScope","hello,model");
return "success";
}
4.使用map向request域对象共享数据
index页: <a th:href="@{/testMap}">测试使用Map集合向request域对象共享数据</a><br>
success页:<a th:text="${testRequestScope}"
@RequestMapping("/testMap")
public String testMap(Map<String,Object> map ){
//使用put方法
map.put("testRequestScope","hello map");
return "success";
}
5.使用ModelMap向request域对象共享数据
index页:<a th:href="@{/testModelMap}">测试使用ModelMap集合向request域对象共享数据</a><br>
success页:<a th:text="${testRequestScope}"
@RequestMapping("/testModelMap")
public String testModelMap(ModelMap modelMap){
//使用addAttribute方法
modelMap.addAttribute("testRequestScope","hello modelMap");
return "success";
}
Model、ModelMap、Map的关系:
Model、ModelMap、Map类型的参数其实本质上都是BindingAwareModelMap类型的。
public class BindingAwareModelMap extend ExtendedModelMap{}
public class ExtendedModelMap extends ModelMap implements Model{}
public class ModelMap extends LinkedHashMap<String,Object>{}
public class LinkedHashMap extends HashMap implements Map{}
public interface Model{}
6.向session域共享数据
index页:<a th:href="@{/testSession}">测试使用ServletAPI向session域对象共享数据</a><br>
success页:<p th:text="${session.testSessionScope}"></p>
@RequestMapping("/testSession")
public String testSession(HttpSession session){
//使用setAttribute方法
session.setAttribute("testSessionScope","hello session");
return "success";
}
7.向application域对象共享数据
index页:<a th:href="@{/testApplication}">测试使用ServletAPI向application域对象共享数据</a><br>
success页:<p th:text="${application.testApplicationScope}"></p>
@RequestMapping("/testApplication")
public String testApplication(HttpSession session){
ServletContext application = session.getServletContext();
//使用setAttribute方法
application.setAttribute("testApplicationScope","hello application");
return "success";
}