OEH
OEH

Reputation: 705

Difference between @ModelAttribute before a method and inside the method argument

what is the difference between those two @ModelAttribute usage?

    public String getMethod(@ModelAttribute UserDetails userDetails){ ... }

and

@ModelAttribute
public UserDetails getAccount(@RequestParam String user, @RequestParam String emailId)

Upvotes: 2

Views: 511

Answers (1)

Ansgar Schulte
Ansgar Schulte

Reputation: 493

In both cases @ModelAttribute will add an attribute to your model (no surprise here). The difference is, that when used on a method, this method will be executed before the appropriate @RequestMapping method is called. You can use that if you want to add commonly attributes (The list for a drop down choice may be a proper example).

In contrast, when used as a parameter annotation, Spring tries to pass an already existing model attribute to your method. In case this doesn't exist, Spring will create a new attribute for you first.

Consult the documentation for details: http://docs.spring.io/spring/docs/4.1.7.RELEASE/spring-framework-reference/html/mvc.html#mvc-ann-modelattrib-methods

Hope that helps you.

Upvotes: 1

Related Questions