What is the meaning of @ModelAttribute annotation at method argument level?

不问归期 提交于 2020-01-01 05:19:13

问题


Spring 3 reference teaches us:

When you place it on a method parameter, @ModelAttribute maps a model attribute to the specific, annotated method parameter

I don't understand this magic spell, because i sure that model object's alias (key value if using ModelMap as return type) passed to the View after executing of the request handler method. Therefore when request handler method executes the model object's name can't be mapped to the method parameter.

To solve this contradiction i went to stackoverflow and found this detailed example. The author of example said:

// The "personAttribute" model has been passed to the controller from the JSP

It seems, he is charmed by Spring reference...

To dispel the charms i deployed his sample app in my environment and cruelly cut @ModelAttribute annotation from method MainController.saveEdit(). As result the application works without any changes! So i conclude: the @ModelAttribute annotation is not needed to pass web form's field values to the argument's fields. Then i stuck to the question: what is the mean of @ModelAttribute annotation? If the only mean is to set alias for model object in View, then why this way better than explicitly adding of object to ModelMap?


回答1:


The point is that @ModelAttribute is optional - if argument is not annotated and its type has no special meaning (i.e. it's not HttpServletRequest, ModelMap and so on), it's treated like @ModelAttribute-annotated argument.

So, @ModelAttribute is effectively needed in two cases:

  • To specify name of the attribute. If @ModelAttribute is omitted or has the empty value, default name is used (type name of the argument with the first letter decapitalized).

  • If type of the argument has a special meaning. For example, if your domain object passed as attribute extends java.security.Principal, you need to annotate it, otherwise Spring will pass a result of HttpServletRequest.getUserPrincipal() instead.

Some people tend to use @ModelAttribute without actual need in order to document the meaning of arguments.



来源:https://stackoverflow.com/questions/4700804/what-is-the-meaning-of-modelattribute-annotation-at-method-argument-level

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!