Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 504
beemaster Avatar asked Jan 15 '11 16:01

beemaster


1 Answers

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.

like image 126
axtavt Avatar answered Sep 19 '22 23:09

axtavt