0
点赞
收藏
分享

微信扫一扫

SpringMVC里的Model、Map、ModelMap以及ModelAndView

小黑Neo 2022-06-09 阅读 148

① Model是什么?

SpringMVC内部使用一个​​org.springframework.ui.Model​​​接口存储的数据模型,它的功能类似于​​java.uitl.Map​​​,但是比Map更好用 ​​org.springframework.ui.ModelMap​​实现Map接口。

SpringMVC在调用方法前会创建一个隐含的数据模型,作为模型数据的存储容器, 成为"隐含模型"。 这个隐形模型类型为​​BindingAwareModelMap​​​,从以下继承树可以看到无轮你用​​Map、ModelMap​​​还是​​Model​​接收都可以!

如果处理方法入参为​​Map、ModelMap或者Model​​类型,SpringMVC会将隐含模型的引用传递给这些入参。

SpringMVC里的Model、Map、ModelMap以及ModelAndView_spring

​Spring Web MVC​​​ 提供​​Model、Map或ModelMap​​让我们能去暴露渲染视图需要的模型数据。

@RequestMapping(value = "/model")
public String createUser(Model model, Map model2, ModelMap model3) {
model.addAttribute("a", "a");
model2.put("b", "b");
model3.put("c", "c");
System.out.println(model == model2);
System.out.println(model2 == model3);
return "success";
}

虽然此处注入的是三个不同的类型(​​Model model, Map model2, ModelMap model3​​),但三者实际是同一个对象。

​AnnotationMethodHandlerAdapter​​​和​​RequestMappingHandlerAdapter​​​将使用​​BindingAwareModelMap​​​作为模型对象的实现,即此处我们的形参(​​Model model, Map model2, ModelMap model3​​​)都是同一个​​BindingAwareModelMap​​实例。

② ModelAndView

​ModelAndView​​​将会返回一个带有数据​​Model​​​以及视图名称​​viewName​​的对象。

如下所示,返回ModelView

@RequestMapping(value = "/mergeModel")
public ModelAndView mergeModel(Model model) {
model.addAttribute("a", "a");//①添加模型数据
ModelAndView mv = new ModelAndView("success");
mv.addObject("a", "update");//②在视图渲染之前更新③处同名模型数据
model.addAttribute("a", "new");//③修改①处同名模型数据
//视图页面的a将显示为"update" 而不是"new"
return mv;
}

从代码中我们可以总结出功能处理方法的返回值中的模型数据(如​​ModelAndView​​)会 合并 功能处理方法形式参数中的模型数据(如Model),但如果两者之间有同名的,返回值中的模型数据会覆盖形式参数中的模型数据。

放到Map中的数据如何传值到前台,以及前台如何取值?

ModelMap对象主要用于传递控制方法处理数据到结果页面,也就是说我们把结果页面上需要的数据放到ModelMap对象中即可,他的作用类似于向request域对象中放入参数。在JSP页面中可以直接使用EL表达式取值。

在没有显示标注注解的情况下,这里参数解析按照​​@ModelAttribute​​处理。如果你在Map上使用了​​@RequestParam​​注解,将有不同处理!


举报

相关推荐

Model和ModelMap的关系

0 条评论