In Spring, @ModelAttribute annotation is used to bind form data to a model object. When this annotation is used, Spring automatically maps the HTTP request parameters to corresponding fields of a model class.
To handle form submissions using @ModelAttribute annotation, we need to follow these steps:
1. Create a form in HTML or JSP page with input fields that match the fields of our model class.
<form action="processForm" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name"><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email"><br>
<label for="message">Message:</label>
<textarea id="message" name="message"></textarea><br>
<input type="submit" value="Submit">
</form>
2. Create a model class with fields that match the form fields.
public class ContactForm {
private String name;
private String email;
private String message;
// getters and setters
}
3. In the Spring controller, handle the form submission with a @PostMapping method.
@PostMapping("/processForm")
public String processForm(@ModelAttribute("contactForm") ContactForm contactForm) {
// do something with the contactForm object
return "successPage";
}
4. In the @PostMapping method, we use @ModelAttribute annotation to bind the form data to a model object. The attribute name is optional and is used to give a name to the model object.
5. Spring automatically maps the form fields to the corresponding fields of the ContactForm object. We can access these fields using getter methods.
6. Do something with the contactForm object and return a view name for further processing.
Overall, Spring’s @ModelAttribute annotation makes it easy to handle form submissions and bind form data to a model object. This can simplify the code and make it easier to work with form submissions in a Spring application.