在SpringMVC中向域对象共享数据的方法有多种
在底层中,这些类型的形参最终都是通过BindingAwareModelMap创建
他们的继承关系如下:
public class BindingAwareModelMap extends ExtendedModelMap{}
public class ExtendedModelMap extends ModelMap implements Model{}
public class ModelMap extends LinkedHashMap<String, Object>{}
1.通过ModelAndView向请求域共享数据
使用ModelAndView时,可以使用其model功能向请求域共享数据
使用view功能设置逻辑视图,但是控制器方法一定要将ModelAndView作为方法的返回值
2.使用Model向请求域共享数据
3.使用ModelMap向请求域共享数据
4.使用Map向请求域共享数据
其中2、3、4的方式底层也都是BindingAwareModelMap
其实无论使用哪种方式,底层模型与视图最后都会被封装到ModelAndView中
实现代码如下:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>首页</title>
</head>
<body>
<hr>
<a th:href="@{/test/mav}">测试通过ModelAndView向请求域共享数据</a><br>
<a th:href="@{/test/model}">测试通过Model向请求域共享数据</a><br>
<a th:href="@{/test/modelMap}">测试通过ModelMap向请求域共享数据</a><br>
<a th:href="@{/test/map}">测试通过Map向请求域共享数据</a>
</body>
</html>
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>首页</title>
</head>
<body>
<h1>success.html</h1>
<p th:text="${testRequestScope}"></p>
</body>
</html>
package com.qcw.controller;
@Controller
public class TestScopeController {
@RequestMapping("/test/mav")
public ModelAndView testMAV(){
/**
* ModelAndView包含Model和View的功能
* Model:向请求域中共享数据
* View:设置逻辑视图实现页面跳转
*/
ModelAndView mav = new ModelAndView();
//向请求域中共享数据
mav.addObject("testRequestScope","hello,ModelAndView");
//设置逻辑视图
mav.setViewName("success");
return mav;
}
@RequestMapping("/test/model")
public String testModel(Model model){
System.out.println(model.getClass().getName());
model.addAttribute("testRequestScope","hello,Model");
return "success";
}
@RequestMapping("/test/modelMap")
public String testModelMap(ModelMap modelMap){
System.out.println(modelMap.getClass().getName());
modelMap.addAttribute("testRequestScope","hello,ModelMap");
return "success";
}
@RequestMapping("/test/map")
public String testMap(Map<String ,Object> map){
//org.springframework.validation.support.BindingAwareModelMap
System.out.println(map.getClass().getName());
map.put("testRequestScope","hello,map");
return "success";
}
}