Java ModelAndView 和 ModelMap 有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3344627/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 22:28:42  来源:igfitidea点击:

What's the difference between ModelAndView and ModelMap?

javaspringspring-mvc

提问by pnut butter

Is ModelMapjust the new name in Spring 3 for a ModelAndView?

是否ModelMap只是新的名称在春季3的ModelAndView

Does the functionality change in Spring 3?

Spring 3 中的功能是否有变化?

Consider this code in a Spring 3 app using a ModelMap:

考虑在 Spring 3 应用程序中使用以下代码ModelMap

 @RequestMapping(value = "/order", method = RequestMethod.GET)
 public final String setup(final ModelMap model)
 {
  model.addAttribute(ORDER, new Order());
  return "setup";
 }

I would like to know what the equivalent use here of ModelAndViewwould be in an older Spring app? Would it just require a name change from ModelMapto ModelAndViewto get this working in Spring 2.5?

我想知道ModelAndView在较旧的 Spring 应用程序中,此处的等效用途是什么?在 Spring 2.5 中是否只需要从ModelMapto更改名称即可ModelAndView使其正常工作?

采纳答案by skaffman

ModelAndView, as its name suggests, contains the model, andthe name of the view. ModelMap, in contract, only contains information about the model.

ModelAndView顾名思义,包含模型视图的名称。ModelMap,在合同中,仅包含有关模型的信息。

Your example would have been written (in "old" Spring) as

你的例子会被写成(在“旧的”Spring中)

 public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
 {
  return new ModelAndView("setup", ORDER, new Order());
 }

回答by Rob Breidecker

@coder247 Someone correct me if I'm wrong, but you don't need to return a ModelMap. Add your attributes to your ModelMap and simply return a String which is the View name.

@coder247 如果我错了,有人会纠正我,但您不需要返回 ModelMap。将您的属性添加到您的 ModelMap 并简单地返回一个字符串,即视图名称。

This is an excellent article that explains how to do this and more... http://www.mkyong.com/spring-mvc/spring-mvc-form-handling-annotation-example/

这是一篇很好的文章,解释了如何做到这一点以及更多... http://www.mkyong.com/spring-mvc/spring-mvc-form-handling-annotation-example/