Spring MVC Tutorial
Core Spring MVC
Spring MVC - Annotation
Spring MVC - Form Handling
Spring MVC with JSTL
Spring MVC with REST API
Spring MVC with Database
Form handling is a core feature in web applications, and Spring MVC provides a comprehensive framework for processing forms. In this guide, I'll walk you through the basics of form handling using Spring MVC:
Ensure you have the Spring MVC dependency in your pom.xml
:
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.3.10</version> </dependency>
Let's say we have a simple User
model:
public class User { private String username; private String password; // Getters and setters... }
Create a controller to handle the form:
@Controller public class UserController { @GetMapping("/register") public String showForm(Model model) { model.addAttribute("user", new User()); return "registerForm"; } @PostMapping("/register") public String submitForm(@ModelAttribute User user, Model model) { // You'd typically save the user to the database here model.addAttribute("user", user); return "registerSuccess"; } }
Create a registration form (registerForm.jsp
):
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> <form:form method="POST" modelAttribute="user"> Username: <form:input path="username" /> <br> Password: <form:password path="password" /> <br> <input type="submit" value="Register" /> </form:form>
Once the form is submitted, it'll be processed by the submitForm
method in the controller, and the result can be displayed in registerSuccess.jsp
:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <h1>Registration Success</h1> <p>Welcome, <c:out value="${user.username}" />! You've successfully registered.</p>
Spring provides support for validation via the Java Validation API (Bean Validation). For this:
<dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>2.0.1.Final</version> </dependency> <dependency> <groupId>org.hibernate.validator</groupId> <artifactId>hibernate-validator</artifactId> <version>6.0.13.Final</version> </dependency>
public class User { @NotEmpty private String username; @Size(min = 8, max = 15) private String password; // Getters and setters... }
@PostMapping("/register") public String submitForm(@Valid @ModelAttribute User user, BindingResult result, Model model) { if (result.hasErrors()) { return "registerForm"; } model.addAttribute("user", user); return "registerSuccess"; }
Display error messages in registerForm.jsp
:
<form:errors path="username" cssClass="error" /> <form:errors path="password" cssClass="error" />
You can also customize error messages by adding messages in a messages.properties
file and configuring a MessageSource
in your Spring configuration.
This is a basic overview of form handling in Spring MVC. You can expand upon this foundation by adding more complex validation, integrating with databases, handling file uploads, and more.
Spring MVC Form Handling Example:
Description: This is a basic example illustrating the handling of a simple HTML form in a Spring MVC application. It involves creating a form, submitting it to a Spring MVC controller, and processing the form data on the server.
Code Snippet: (HTML Form)
<!-- simpleForm.jsp --> <form action="/submitForm" method="post"> <label for="username">Username:</label> <input type="text" id="username" name="username" /> <button type="submit">Submit</button> </form>
Processing Forms with Spring MVC:
Description: This example expands on the basic form handling by providing a Spring MVC controller method to process the submitted form data.
Code Snippet: (Controller Method)
@Controller public class FormController { @PostMapping("/submitForm") public String processForm(@RequestParam("username") String username) { // Process form data return "formResult"; } }
Spring MVC Form Submission and Validation:
Description: This example includes form validation using Spring MVC annotations. It shows how to validate form fields and handle validation errors.
Code Snippet: (Model Attribute with Validation)
public class UserForm { @NotBlank(message = "Username is required") private String username; // Getter and Setter } @Controller public class ValidationController { @PostMapping("/submitForm") public String submitForm(@Valid @ModelAttribute("userForm") UserForm userForm, BindingResult result) { // Handle validation errors if (result.hasErrors()) { return "errorPage"; } // Process form data return "formResult"; } }
Handling Multiple Forms in Spring MVC:
Description: This example demonstrates how to handle multiple forms in a Spring MVC controller. It involves submitting different forms to distinct controller methods.
Code Snippet: (Controller Methods for Different Forms)
@Controller public class MultipleFormsController { @PostMapping("/submitForm1") public String processForm1(/* form fields */) { // Process form 1 data return "form1Result"; } @PostMapping("/submitForm2") public String processForm2(/* form fields */) { // Process form 2 data return "form2Result"; } }
Form Binding in Spring MVC:
Description: This example uses form binding to automatically bind form fields to a model object in a Spring MVC controller.
Code Snippet: (Model Attribute and Controller Method)
public class User { private String username; // Getter and Setter } @Controller public class BindingController { @PostMapping("/submitForm") public String submitForm(@ModelAttribute("user") User user) { // Access user.getUsername() for form data return "formResult"; } }
Customizing Form Handling in Spring MVC:
Description: This example illustrates how to customize form handling in Spring MVC by using custom converters, formatters, or initBinder methods.
Code Snippet: (Custom Converter)
public class CustomDateConverter implements Converter<String, Date> { @Override public Date convert(String source) { // Custom conversion logic return DateUtils.parse(source); } } @Controller public class CustomController { @InitBinder public void initBinder(WebDataBinder binder) { binder.addCustomFormatter(new DateFormatter("yyyy-MM-dd")); } @PostMapping("/submitForm") public String submitForm(@RequestParam("dob") Date dob) { // Process form data with custom date conversion return "formResult"; } }
Thymeleaf Form Handling in Spring MVC:
Description: This example demonstrates how to use Thymeleaf to render and handle forms in a Spring MVC application.
Code Snippet: (Thymeleaf Form)
<!-- th:object is used for form backing object --> <form action="/submitForm" method="post" th:object="${user}"> <label for="username">Username:</label> <input type="text" id="username" name="username" th:field="*{username}" /> <button type="submit">Submit</button> </form>
Spring MVC Form Validation and Error Handling:
Description: This example extends the form validation example to include proper error handling in the view.
Code Snippet: (Thymeleaf with Validation Errors)
<!-- Display validation errors using Thymeleaf --> <form action="/submitForm" method="post" th:object="${user}"> <label for="username">Username:</label> <input type="text" id="username" name="username" th:field="*{username}" /> <span th:if="${#fields.hasErrors('username')}" th:errors="*{username}"></span> <button type="submit">Submit</button> </form>