<a th:href="@{/testRequestByServletAPI}">通过servletAPI向request域对象共享数据a><br/>
@RequestMapping("/testRequestByServletAPI")
//使用servletAPI向request域对象共享数据
public String testRequestByServletAPI(HttpServletRequest request){
request.setAttribute("testRequestScope", "hello, servletAPI");
return "success";
}
<p th:text="${testRequestScope}">p>
<a th:href="@{/testModelAndView}">通过ModelAndView向request域对象共享数据a><br/>
@RequestMapping("/testModelAndView")
public ModelAndView testModelAndView(){
ModelAndView mav = new ModelAndView();
//处理模型数据,即向请求域request共享数据
mav.addObject("testRequestScope", "hello, ModelAndView");
//设置视图名称
mav.setViewName("success");
return mav;
}
注意:
- 返回值必须是 ModelAndView;
<a th:href="@{/testModel}">通过Model向request域对象共享数据a><br/>
@RequestMapping("/testModel")
public String testModel(Model model){
model.addAttribute("testRequestScope", "hello, Model");
return "success";
}
<a th:href="@{/testMap}">通过Map向request域对象共享数据a><br/>
@RequestMapping("/testMap")
public String testMap(Map<String, Object> map){
map.put("testRequestScope", "hello, Map");
return "success";
}
<a th:href="@{/testModelMap}">通过ModelMap向request域对象共享数据a><br/>
@RequestMapping("/testModelMap")
public String testModelMap(ModelMap modelMap){
modelMap.addAttribute("testRequestScope", "hello, ModelMap");
return "success";
}
Model、ModelMap、Map 类型的参数其实本质上都是 BindingAwareModelMap 类型的。
@RequestMapping("/testModel")
public String testModel(Model model){
model.addAttribute("testRequestScope", "hello, Model");
System.out.println(model.getClass().getName());
//org.springframework.validation.support.BindingAwareModelMap
return "success";
}
@RequestMapping("/testMap")
public String testMap(Map<String, Object> map){
map.put("testRequestScope", "hello, Map");
System.out.println(map.getClass().getName());
//org.springframework.validation.support.BindingAwareModelMap
return "success";
}
@RequestMapping("/testModelMap")
public String testModelMap(ModelMap modelMap){
modelMap.addAttribute("testRequestScope", "hello, ModelMap");
System.out.println(modelMap.getClass().getName());
//org.springframework.validation.support.BindingAwareModelMap
return "success";
}
public interface Model{}
public class ModelMap extends LinkedHashMap
{} public class ExtendedModelMap extends ModelMap implements Model {}
public class BindingAwareModelMap extends ExtendedModelMap {}
<a th:href="@{/testSession}">通过servletAPI向session域对象共享数据a><br/>
@RequestMapping("/testSession")
public String testSession(HttpSession httpSession){
httpSession.setAttribute("testSessionScope", "hello, session");
return "success";
}
<p th:text="${session.testSessionScope}">p>
<a th:href="@{/testApplication}">通过servletAPI向application域对象共享数据a><br/>
@RequestMapping("/testApplication")
public String testApplication(HttpSession httpSession){
ServletContext application = httpSession.getServletContext();
application.setAttribute("testApplicationScope", "hello, application");
return "success";
}
<p th:text="${application.testApplicationScope}">p>