文章目录
1. 四大域对象
域对象主要用在web应用中,负责存储数据,通俗的讲就是这个对象本身可以存储一定范围内的所有数据,通过它就能获取和存储数据,
可以理解为万能的一个属性,只要调用它就可以获得这个范围(域)内的想要的数据,也可以修改删除数据,当然也可以给这个域添加数据
四大域对象的作用范围:
- ServletContext域对象:整个web项目(一个web项目只有一个ServletContext对象)
- request域对象:一次请求的多次转发中有效
request.getRequestDispatcher(“/资源路径”).forward(request,response) - session域对象:一次会话(默认)
第一次执行getSession方法创建对象后会响应给浏览器一个存储了JSESSIONID的cookie,下一次请求资源浏览 器会携带着JSESSIONID给服务器,再次执行getSession方法服务器会拿着JSESSIONID找到之前的session对象 - pageContext域对象:当前jsp页面
2. 使用ServletAPI向request域对象共享数据
@RequestMapping("/testServletAPI")
public String testServletAPI(HttpServletRequest request){
request.setAttribute("testScope", "hello,servletAPI");
return "success";
}
3. 使用ModelAndView向request域对象共享数据
@RequestMapping("/testModelAndView")
public ModelAndView testModelAndView(){
/**
* ModelAndView有Model和View的功能
* Model主要用于向请求域共享数据
* View主要用于设置视图,实现页面跳转
*/
ModelAndView mav = new ModelAndView();
//向请求域共享数据
mav.addObject("testScope", "hello,ModelAndView");
//设置视图,实现页面跳转
mav.setViewName("success");
return mav;
}
4. 使用Model向request域对象共享数据
@RequestMapping("/testModel")
public String testModel(Model model){
model.addAttribute("testScope", "hello,Model");
return "success";
}
5. 使用map向request域对象共享数据
@RequestMapping("/testMap")
public String testMap(Map<String, Object> map){
map.put("testScope", "hello,Map");
return "success";
}
6. 使用ModelMap向request域对象共享数据
@RequestMapping("/testModelMap")
public String testModelMap(ModelMap modelMap){
modelMap.addAttribute("testScope", "hello,ModelMap");
return "success";
}
7. Model、ModelMap、Map的关系
通过.getClass().getName()获取真正实现实例化的全类名
Model、ModelMap、Map类型的参数其实本质上都是 BindingAwareModelMap 类型的
- Model 没有继承其他接口,是SpringMVC中最顶层接口
- Map 就是 JDK 中map
- ModelMap 继承于 LinkedHashMap,LinkedHashMap 有实现了 Map,所以 ModelMap 是 Map 接口实现类
- BindingAwareModelMap 继承了 ExtendedModelMap
- ExtendedModelMap 继承了 ModelMap,实现了 Model 接口
public interface Model{}
public class ModelMap extends LinkedHashMap<String, Object> {}
public class ExtendedModelMap extends ModelMap implements Model {}
public class BindingAwareModelMap extends ExtendedModelMap {}
控制器方法执行后都会统一返回MAV对象
8. 向session域共享数据
@RequestMapping("/testSession")
public String testSession(HttpSession session){
session.setAttribute("testSessionScope", "hello,session");
return "success";
}
9. 向application域共享数据
@RequestMapping("/testApplication")
public String testApplication(HttpSession session){
ServletContext application = session.getServletContext();
application.setAttribute("testApplicationScope", "hello,application");
return "success";
}