Form Handling & Validation
Forms are how users enter data in web applications. Spring MVC makes form handling easy with @ModelAttribute and provides validation using Bean Validation (JSR-380).
Step 1: Add validation dependencies (if using Maven):
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
Step 2: Add validation annotations to your model
public class User {
@NotBlank(message = "Name is required")
private String name;
@Email(message = "Invalid email format")
@NotBlank(message = "Email is required")
private String email;
@Min(value = 18, message = "Age must be at least 18")
@Max(value = 100, message = "Age must be less than 100")
private int age;
// getters and setters
}
Step 3: Create controller with form handling and validation
@Controller
public class UserController {
// Show registration form
@GetMapping("/register")
public String showForm(Model model) {
model.addAttribute("user", new User());
return "register";
}
// Process registration form with validation
@PostMapping("/register")
public String processForm(
@Valid @ModelAttribute("user") User user,
BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
// If validation fails, go back to form
return "register";
}
// Save user to database (not shown)
return "success";
}
}
Step 4: Create the form view (register.jsp or register.html)
<form action="/register" method="post">
<label>Name:</label>
<input type="text" name="name" value="${user.name}"/>
<errors path="name"/><br/>
<label>Email:</label>
<input type="text" name="email" value="${user.email}"/>
<errors path="email"/><br/>
<label>Age:</label>
<input type="number" name="age" value="${user.age}"/>
<errors path="age"/><br/>
<button type="submit">Register</button>
</form>
Key points:
- @Valid – triggers validation on the User object.
- BindingResult – must come right after @Valid parameter. Contains validation errors.
- hasErrors() – checks if validation failed.
- Spring automatically shows error messages in view (with <errors> tag).
Two Minute Drill
- @ModelAttribute binds form data to Java object.
- Use validation annotations like @NotBlank, @Email, @Min.
- @Valid enables validation on the model object.
- BindingResult captures validation errors.
- Always check hasErrors() before processing data.
Need more clarification?
Drop us an email at career@quipoinfotech.com
