文章目录
1、使用ServletAPI向request域对象共享数据
==HttpServletRequest是原生的API,不建议使用原生API来向Request域对象共享数据,==SpringMVC提供了自己的API来进行域对象共享数据,从下面的第2条开始便是。
@RequestMapping("/testServletAPI")
public String testServletAPI(HttpServletRequest request){
request.setAttribute("testScope", "hello,servletAPI");
return "success";
}
2、使用ModelAndView向request域对象共享数据(重要)
Model主要指得是向域对象中共享数据的过程
View主要指得是最终所设置的视图名称经过视图解析器解析跳转到页面的过程
ModelAndView对象必须作为方法的返回值进行返回
不管使用的是什么方式向request域对象中共享数据,最终都要把数据封装到ModelAndView中
package com.rqs.mvc.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class ScopeController {
@RequestMapping("/testModelAndView")
public ModelAndView testModelAndView(){
/**
* ModelAndView有Model和View的功能
* Model主要用于向请求域共享数据
* View主要用于设置视图,实现页面跳转
*/
ModelAndView mav = new ModelAndView();
//处理模型数据,即向请求域共享数据
mav.addObject("testScope", "hello,ModelAndView");
//设置视图名称,实现页面跳转
mav.setViewName("success");
return mav;
}
}
3、使用Model向request域对象共享数据
@RequestMapping("/testModel")
public String testModel(Model model){
model.addAttribute("testScope", "hello,Model");//(attributeName,attributeValue)
return "success";
}
4、使用map向request域对象共享数据
map的数据类型要知道:<String, Object>
@RequestMapping("/testMap")
public String testMap(Map<String, Object> map){
map.put("testScope", "hello,Map");
return "success";
}
5、使用ModelMap向request域对象共享数据
类似于3中使用Model向request域对象共享数据
@RequestMapping("/testModelMap")
public String testModelMap(ModelMap modelMap){
modelMap.addAttribute("testScope", "hello,ModelMap");
return "success";
}
6、Model、ModelMap、Map的关系
Model是一个接口
ModelMap继承了LinkedHashMap
ExtendedModelMap继承了ModelMap并且实现了Model接口
BindingAwareModelMap继承了ExtendedModelMap,所以BindingAwareModelMap可以实例化ModelMap和Model,又因为ModelMap继承了LinkedHashMap,LinkedHashMap实现了Map,因此BindingAwareModelMap也可以实例化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 {}
7、向session域共享数据
向session域对象中共享数据时,建议使用原生API,即HttpSession
@RequestMapping("/testSession")
public String testSession(HttpSession session){
session.setAttribute("testSessionScope", "hello,session");
return "success";
}
8、向application(指的就是ServletContext,整个应用)域共享数据
Request,Session都可以获取ServletContext,例如session.getServletContext(),所以可以通过设置形参(HttpSession session)来使用getServletContext()方法得到ServletContext
@RequestMapping("/testApplication")
public String testApplication(HttpSession session){
ServletContext application = session.getServletContext();
application.setAttribute("testApplicationScope", "hello,application");
return "success";
}