What is @ModelAttribute in Spring MVC?
In Spring MVC, the @ModelAttribute
annotation is used to bind request parameters to method arguments in controller methods.
Here's an example of how you can use the @ModelAttribute
annotation to bind request parameters to a method argument:
@Controller
public class MyController {
@RequestMapping(value = "/foo", method = RequestMethod.GET)
public String handleRequest(@ModelAttribute("param1") String param1,
@ModelAttribute("param2") int param2,
Model model) {
// use the request parameters here
return "viewName";
}
}
In this example, the handleRequest()
method is mapped to the /foo
URL and accepts two request parameters: param1
and param2
. The @ModelAttribute
annotation is used to bind the values of these parameters to the param1
and param2
method arguments.
The @ModelAttribute
annotation can also be used to bind the result of a method to a specific attribute in the model. Here's an example of how you can do this:
@Controller
public class MyController {
@ModelAttribute("attributeName")
public String populateAttribute() {
return "Attribute Value";
}
@RequestMapping(value = "/foo", method = RequestMethod.GET)
public String handleRequest(Model model) {
// the "attributeName" attribute has already been added to the model
return "viewName";
}
}
In this example, the populateAttribute()
method is annotated with @ModelAttribute
and is invoked before the handleRequest()
method is called. The result of the populateAttribute()
method is added to the model under the name "attributeName".
I hope this helps! Let me know if you have any questions.