Annotations
Name | Description |
@Model | Interface, holder for model attributes |
@ModelMap | Class, in ModelMap attibute key can be omitted and the value of the attribute will be use to generate the key. |
@ModelAndView | ModelAndView it’s a container for both View object and ModelMap |
@ModelAttribute
Annotation that binds a method parameter or method return method to a named model attribute.
Method level
The purpose of the method is to add one or more model attributes. This methods can’t be directly mapped to requests. Spring MVC will always make a call to this method before any request handler controllers.
@ModelAttribute
public void addAttributes(Model model) {
model.addAttribute("msg", "Welcome to the Netherlands!");
}
Method argument
The argument will be retrieved from the model
@RequestMapping(value = "/addEmployee", method = RequestMethod.POST)
public String submit(@ModelAttribute("employee") Employee employee) {
// Code that uses the employee object
return "employeeView";
}
https://www.baeldung.com/spring-mvc-and-the-modelattribute-annotation
BindingResult
[BindingResult
] is Spring’s object that holds the result of the validation and binding and contains errors that may have occurred. The BindingResult
must come right after the model object that is validated or else Spring will fail to validate the object and throw an exception.
When Spring sees @Valid
, it tries to find the validator for the object being validated. Spring automatically picks up validation annotations if you have “annotation-driven” enabled. Spring then invokes the validator and puts any errors in the BindingResult
and adds the BindingResult to the view model.
@PostMapping("/register")
public String doPost(AuthUserDetails user, BindingResult bindingResult) {
if (securityService.userExists(user.getUsername())) {
return "user/userExists";
}
securityService.addUser(user);
return "redirect:/login";
}
References
https://www.baeldung.com/spring-mvc-model-model-map-model-view
https://www.baeldung.com/spring-mvc-and-the-modelattribute-annotation