As a Method Argument
When used as a method argument, it indicates the argument should be
retrieved from the model. When not present, it should be first
instantiated and then added to the model and once present in the
model, the arguments fields should be populated from all request
parameters that have matching names.
In the code snippet that follows the employee model attribute is
populated with data from a form submitted to the addEmployee endpoint.
Spring MVC does this behind the scenes before invoking the submit
method:
@RequestMapping(value = "/addEmployee", method = RequestMethod.POST)
public String submit(@ModelAttribute("employee") Employee employee) {
// Code that uses the employee object
return "employeeView";
}
Later on in this article we will see a complete example of how to use
the employee object to populate the employeeView template.
So, it binds the form data with a bean. The controller annotated with
@RequestMapping
can have custom class argument(s) annotated with @ModelAttribute.
This is what is commonly known as data binding in Spring-MVC, a common
mechanism that saves you from having to parse each form field
individually.
In general, Spring-MVC will always make a call first to that method,
before it calls any request handler methods. That is, @ModelAttribute
methods are invoked before the controller methods annotated with
@RequestMapping are invoked. The logic behind the sequence is that,
the model object has to be created before any processing starts inside
the controller methods.