1. 使用ServletAPI向request域对象共享数据
@RequestMapping("/testServletAPI")
public String testServletAPI(HttpServletRequest request){
request.setAttribute("key1", "value1");
return "success";
}
2. 使用ModelAndView向request域对象共享数据
@RequestMapping("/testModelAndView")
public ModelAndView testModelAndView(){
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("key1", "value1");
modelAndView.setViewName("success");
return modelAndView;
}
3. 使用Model向request域对象共享数据
@RequestMapping("/testModel")
public String testModel(Model model){
model.addAttribute("key1", "value1");
return "success";
}
4. 使用map向request域对象共享数据
@RequestMapping("/testMap")
public String testMap(Map<String, Object> map){
map.put("key1", "value1");
return "success";
}
5. 使用ModelMap向request域对象共享数据
@RequestMapping("/testModelMap")
public String testModelMap(ModelMap modelMap){
modelMap.addAttribute("key1", "value1");
return "success";
}
6. 向session域共享数据
@RequestMapping("/testSession")
public String testSession(HttpSession session){
session.setAttribute("key1", "value1");
return "success";
}
7. 向application域共享数据
@RequestMapping("/testApplication")
public String testApplication(HttpSession session){
ServletContext application = session.getServletContext();
application.setAttribute("key1", "value1");
return "success";
}
8. request域、session域、application域
request (HttpServletRequest 类):一次请求内有效
session (HttpSession 类):一个会话范围内有效(跟服务器关闭没有关系,只跟浏览器是否关闭有关系)
application (ServletContext 类): 整个 web 工程范围内都有效(只跟服务器是否关闭有关系)