SpringMVC域对象共享数据

109 阅读1分钟

域对象共享数据

<p th:text="${testRequestScope}"></p>

通过ServletApi共享数据

@RequestMapping("/testRequestScope")
public String testRequestScope(HttpServletRequest request){
    request.setAttribute("testRequestScope","张三");
    return"success";
}
<a th:href="@{/testRequestScope}" method="get">  测试ServiteApi域对象共享数据</a><br>

image.png

通过ModelAndView共享数据

@RequestMapping("/testModelAndView")
public ModelAndView testModelAndView(){
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.setViewName("success");
    modelAndView.addObject("testRequestScope","hello modelandView");
    return modelAndView;
}
<a th:href="@{/testModelAndView}" method="get">  测试testModelAndView域对象共享数据</a><br>

image.png

通过Model共享数据

@RequestMapping("/testModel")
public String testModel(Model model){
   model.addAttribute("testRequestScope","hello model");
    return "success";
}
<a th:href="@{/testModel}" method="get">  测试testModel域对象共享数据</a><br>

image.png

通过Map共享数据

@RequestMapping("/testMap")
public String testMap(Map<String,Object> map){
   map.put("testRequestScope","hello map");
    return "success";
}
<a th:href="@{/testMap}" method="get">  测试testMap域对象共享数据</a><br>

image.png

通过ModelMap共享数据

@RequestMapping("/testModelAndMap")
public String testModelMap(ModelMap map){
    map.addAttribute("testRequestScope","hello ModelMap");
    return "success";
}
<a th:href="@{/testModelAndMap}" method="get">  测试testModelAndMap域对象共享数据</a><br>

image.png

model modelMap Map的关系

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 testSession(HttpSession session){
    session.setAttribute("testSession","hello Session");
    return "success";
}
<p th:text="${session.testSession}"></p>

image.png

向Application中共享对象

@RequestMapping("/testApplication")
public String testApplication(HttpSession session){
    ServletContext servletContext = session.getServletContext();
    servletContext.setAttribute("testApplication","hello Application");
    return "success";
}
<p th:text="${application.testApplication}"></p>

image.png