Spring MVC 可以在控制器方法中直接获取 Servlet 原生 Web 资源,只需要在方法定义时添加HttpServletRequest ⼊参即可,在方法体中直接使用request 对象。
@RequestMapping("/test/servletAPI")
public String testSevletAPI(HttpServletRequest request) {
request.setAttribute("testRequestScope","hello,servletAPI");
return "success";
}
与 Map 或者 Model 不同的是,ModelAndView 不但包含业务数据,同时也封装了视图信息,如果使用ModelAndView 来处理业务数据,控制器方法的返回值必须是 ModelAndView 对象。
@RequestMapping("/test/modelandview")
public ModelAndView testModelAndView() {
ModelAndView mav=new ModelAndView();
/**
* ModelAndView包含Model和View的功能
* Model:向请求域中共享数据
* View:设置逻辑视图实现页面跳转
*/
//向请求域中共享数据
mav.addObject("testRequestScope","hello,ModelAndView");
//设置逻辑视图实现页面跳转
mav.setViewName("success");
System.out.println(mav.getClass().getName());
return mav;
}
@RequestMapping(value="/test/model")
public String testModel(Model model) {
model.addAttribute("testRequestScope","hello,model");
System.out.println(model.getClass().getName());
//org.springframework.validation.support.BindingAwareModelMap
return "success";
}
Spring MVC 在调⽤控制器方法之前会创建⼀个隐含对象作为业务数据的存储容器,设置控制器⽅法的⼊参为 Map 类型,Spring MVC 会将隐含对象的引用传递给⼊参。
@RequestMapping("/test/map")
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("/test/modelmap")
public String testModelMap(ModelMap modelMap) {
modelMap.addAttribute("testRequestScope","hello,modelmap");
System.out.println(modelMap.getClass().getName());
//org.springframework.validation.support.BindingAwareModelMap
return "success";
}
Model、ModelMap、Map类型的参数其实本质上都是 BindingAwareModelMap 类型的
public interface Model{} public class ModelMap extends
LinkedHashMap{} public class ExtendedModelMap extends
ModelMap implements Model {} public class BindingAwareModelMap extends
ExtendedModelMap {}
@RequestMapping("/test/session")
public String testSession(HttpSession session) {
session.setAttribute("testRequestScope","hello,session");
return "success";
}
@RequestMapping("/test/application")
public String testApplication(HttpSession session) {
ServletContext appliation=session.getServletContext();
appliation.setAttribute("testRequestScope","hello,application");
return "success";
}