关于Spring MVC中org.springframework.web.servlet.ModelAndView, org.springframework.ui.ModelMap 和 org.springframework.ui.Model的使用说明。
Maven 依赖
首先从spring-context的pom依赖开始,包含ModelMap 和 Model
1 2 3 4 5
| <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.3.11.RELEASE</version> </dependency>
|
最新版本 https://search.maven.org/classic/#search
ModelAndView则是在spring-web中
1 2 3 4 5
| <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.3.11.RELEASE</version> </dependency>
|
Model
Model接口是存放属性的容器,这些属性可以用来渲染views,设计的目的是用来添加属性的。注意Model是没有get数据的方法的。
包含方法
1 2 3 4 5 6 7 8
| Model addAttribute addAttribute addAllAttributes addAllAttributes mergeAttributes containsAttribute asMap
|
同时 model 可以合并 map :
1 2 3 4 5 6 7 8
| @GetMapping("/showViewPage") public String passParametersWithModel(Model model) { Map<String, String> map = new HashMap<>(); map.put("spring", "mvc"); model.addAttribute("message", "Baeldung"); model.mergeAttributes(map); return "viewPage"; }
|
ModelMap
继承了 LinkedHashMap<String, Object>,是用来创建页面使用的模型数据的,可以把属性数据如同map一样管理。
1 2 3 4 5 6 7
| ModelMap extends LinkedHashMap<String, Object> addAttribute addAttribute addAllAttributes addAllAttributes mergeAttributes containsAttribute
|
ps. 作用类似于model,但是丰富了属性的管理(因为是继承了Map)。
1 2 3 4 5 6
| @GetMapping("/printViewPage") public String passParametersWithModelMap(ModelMap map) { map.addAttribute("welcomeMessage", "welcome"); map.addAttribute("message", "Baeldung"); return "viewPage"; }
|
ModelAndView
同时包含模型和视图路由的模型。可以参见成员属性
1 2 3 4 5 6 7
| @Nullable private Object view;
@Nullable private ModelMap model;
|
- 设置view的路由
- 设置渲染view的模型
exp:
1 2 3 4 5 6
| @GetMapping("/goToViewPage") public ModelAndView passParametersWithModelAndView() { ModelAndView modelAndView = new ModelAndView("viewPage"); modelAndView.addObject("message", "Baeldung"); return modelAndView; }
|
使用
Model 和 ModelMap 的实例都是spirng mvc框架来自动创建并作为控制器 方法参数 传入,用户无需自己创建。而且需要 return 返回指定的页面路径。
1 2 3 4 5 6 7
| @RequestMapping("hello") public String hello(Model model) { model.addAttribute("name", "forg"); return "hello"; }
|
ModelAndView的实例是需要手动new的,这也是和ModelMap的一个区别。
而且,ModelAndView 可以自己寻址,只需要return 返回其对象即可。
1 2 3 4 5 6 7 8 9 10 11
| @RequestMapping("hello") public ModelAndView hello(){ ModelAndView mav = new ModelAndView(); mav.addObject("name", "forg"); mav.setViewName("hello"); return mav; }
|
参考
Model、ModelMap和ModelAndView的使用详解
https://blog.csdn.net/ITBigGod/article/details/79685610
What are the differences between Model, ModelMap, and ModelAndView?
https://stackoverflow.com/questions/18486660/what-are-the-differences-between-model-modelmap-and-modelandview
Model, ModelMap, and ModelView in Spring MVC
https://www.baeldung.com/spring-mvc-model-model-map-model-view