Java Spring 中的 ModelMap 使用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2902706/
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
ModelMap usage in Spring
提问by Anna
What are the benifits of using ModelMap instead of a simple Map in Spring MVC. I see in the code implementation that they put the datatype of the attribute added in the map as key instead to be made available on the form.
在 Spring MVC 中使用 ModelMap 而不是简单的 Map 有什么好处。我在代码实现中看到,他们将添加到地图中的属性的数据类型作为键,而不是在表单上可用。
Can anyone explain with an example.
任何人都可以用一个例子来解释。
采纳答案by skaffman
ModelMap
subclasses LinkedHashMap
, and provides some additional conveniences to make it a bit easier to use by controllers
ModelMap
子类LinkedHashMap
,并提供了一些额外的便利,使其更容易被控制器使用
addAttribute
can be called with just a value, and the map key is then inferred from the type.- The
addAttribute
methods all return theModelMap
, so you can chain method called together, e.g.modelMap.addAttribute('x', x).addAttribute('y',y)
- The
addAttribute
methods checks that the values aren't null - The generic type of
ModelMap
is fixed atMap<String, Object>
, which is the only one that makes sense for a view model.
addAttribute
可以只用一个值调用,然后从类型推断映射键。- 这些
addAttribute
方法都返回ModelMap
,因此您可以将方法链接在一起调用,例如modelMap.addAttribute('x', x).addAttribute('y',y)
- 该
addAttribute
方法检查该值不为空 - 的泛型类型
ModelMap
固定在Map<String, Object>
,这是唯一对视图模型有意义的类型。
So nothing earth-shattering, but enough to make it a bit nicer than a raw Map
. Spring will let you use either one.
所以没有什么惊天动地的,但足以使它比原始Map
. Spring 会让你使用任何一种。
You can also use the Model
interface, which provides nothing other than the addAttribute
methods, and is implemented by the ExtendedModelMap
class which itself adds further conveniences.
你也可以使用Model
接口,它只提供addAttribute
方法,并且由ExtendedModelMap
类实现,它本身增加了更多的便利。
回答by Michael Jiang
ModelMap.addAttribute
will do NULL check, ModelMap.put
is inherit from LinkedHashMap
ModelMap.addAttribute
将做 NULL 检查,ModelMap.put
是从 LinkedHashMap 继承的
回答by Michael Jiang
ModalMap extends LinkedHashMap
ModalMap 扩展了 LinkedHashMap
Implementation of Map for use when building model data for use with UI tools. Supports chained calls and generation of model attribute names.
在构建模型数据以与 UI 工具一起使用时使用 Map 的实现。支持链式调用和模型属性名称的生成。
This class serves as generic model holder for both Servlet and Portlet MVC, but is not tied to either of those. Check out the Model interface for a Java-5-based interface variant that serves the same purpose.
此类充当 Servlet 和 Portlet MVC 的通用模型持有者,但不与其中任何一个相关联。查看 Model 接口,了解用于相同目的的基于 Java-5 的接口变体。