域对象共享数据
使用 resvletAPI 向 request 域对象共享数据
@Controller
public class HelloController {
@RequestMapping("/test")
public String test(HttpServletRequest request){
request.setAttribute("testScope", "hello, servletAPI");
return "success";
}
}
<!-- thymeleaf 获取域对象数据 -->
<p th:text="${testScope}"></p>
使用 ModelAndView 向 request 域对象共享数据
@RequestMapping("/testMAV")
public ModelAndView testMAV(){
ModelAndView mav = new ModelAndView();
mav.addObject("MAV", "hello,ModelAndView");
mav.setViewName("success");
return mav;
}
TIP
所有域对象共享数据的方法最终都会封装进 ModelAndView 对象
使用 Model 向 request 域对象共享数据
@RequestMapping("/testModel")
public String testModel(Model model){
model.addAttribute("test", "hello,model");
return "success";
}
使用 Map 向 request 域对象共享数据
@RequestMapping("/testModel")
public String testModel(Map<String, Object> map){
map.put("test", "hello,map");
return "success";
}
使用 ModelMap 向域对象共享数据
@RequestMapping("/testModelMap")
public String testModel(ModelMap map){
map.put("test", "hello,ModelMap");
return "success";
}
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 testModel(HttpSession session){
session.setAttribute("test", "Hello,world");
return "success";
}
<p th:text="${session.test}"></p>
向 application 域共享数据
<p th:text="${application.test}"></p>
@RequestMapping("/testApplication")
public String testModel(HttpSession session){
ServletContext application = session.getServletContext();
application.setAttribute("test", "hello,application");
return "success";
}