In Spring Boot, the @ModelAttribute annotation is primarily used for two purposes: binding request parameters to data models and sharing data models across multiple requests.
1. Binding request parameters to data models
@ModelAttribute can be applied to method parameters, enabling Spring to automatically bind request parameters to Java objects. This is a highly useful feature as it eliminates the need for manual parsing and assignment of request parameters. For example, if we have a form where users need to input their name and email, we can create a corresponding Java class to represent this form:
javapublic class UserForm { private String name; private String email; // getters and setters }
Then, in the controller method, use @ModelAttribute to automatically populate this object:
java@PostMapping("/submitUserForm") public String submitUserForm(@ModelAttribute UserForm userForm) { // Save userForm data or perform other operations return "formSubmitted"; }
This way, when the form is submitted, Spring automatically populates the UserForm object with the form data, and we can use this object within the method.
2. Sharing data models across multiple requests
@ModelAttribute can also be used on methods. This usage is mainly for sharing data across multiple requests. For example, if we want to access the current logged-in user information across multiple requests, we can use @ModelAttribute to set this user information in a common method:
java@ModelAttribute("currentUser") public User getCurrentUser() { // Assume this is the logic to retrieve the logged-in user information return userService.getCurrentUser(); }
After this configuration, every view and controller method can access the user information via the model name currentUser, making it convenient to display user-related information in views or perform user permission checks in controllers.
In summary, the @ModelAttribute annotation plays a crucial role in Spring Boot by simplifying data binding operations to enhance development efficiency and enabling data sharing across different requests through the model sharing mechanism.