Following example shows how to use JSR 303/349/380 Bean Validation API in Spring Boot. The implementation of Bean Validation API should be on the classpath; we are using hibernate-validator in this example. We are also going to use Thymeleaf views.
Example
Using validation annotations
package com.logicbig.example;
import org.springframework.format.annotation.DateTimeFormat;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Past;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import java.time.LocalDate;
public class Employee {
@NotNull
@Size(min = 5, max = 50)
private String name;
@Pattern(regexp = "Admin|IT|Sales|Accounts")
private String dept;
@Past
@NotNull
@DateTimeFormat(pattern = "yyyy-MM-dd")
private LocalDate dateOfBirth;
.............
}
In above bean we are also using spring specific @DateTimeFormat annotation on 'dateOfBirth' field. This annotation is used by the Spring conversion service to convert the input string to the date object and vice-versa. After conversion Bean validation annotations are used to performed the validations.
MVC Controller
@Controller
public class EmployeeController {
//todo replace this with employee DAO/repository.
private static List<Employee> employeeList = new ArrayList<>();
@PostMapping("/")
public String handlePostRequest(@Valid Employee employee, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return "employee-form";
}
employeeList.add(employee);
return "redirect:/employees";
}
@GetMapping("/")
public String handleGetRequest(Employee employee) {
return "employee-form";
}
@GetMapping("/employees")
public String handleGetRequest(Model model) {
model.addAttribute("employees", employeeList);
return "employee-view";
}
}
Thymeleaf views
src/main/resources/templates/employee-form.html<html>
<head>
<style>
table.emp-form td:nth-child(3){color:red;}
</style>
</head>
<body>
<form action="#" th:action="@{/}" th:object="${employee}" method="post">
<table class="emp-form">
<tr>
<td>Name:</td>
<td><input type="text" th:field="*{name}"/></td>
<td th:if="${#fields.hasErrors('name')}" th:errors="*{name}">Name Error</td>
</tr>
<tr>
<td>Department:</td>
<td><input type="text" th:field="*{dept}"/></td>
<td th:if="${#fields.hasErrors('dept')}" th:errors="*{dept}">Department Error</td>
</tr>
<tr>
<td>Date Of Birth:</td>
<td><input type="text" th:field="*{dateOfBirth}"/></td>
<td th:if="${#fields.hasErrors('dateOfBirth')}" th:errors="*{dateOfBirth}">Date Of Birth Error</td>
</tr>
<tr>
<td>
<button type="submit">Submit</button>
</td>
</tr>
</table>
</form>
</body>
</html>
src/main/resources/templates/employee-view.html<html>
<head>
<style>
table.emp-table{width:100%;}
table.emp-table td {border:solid 1px #aaa;}
table.emp-table th {border:solid 1px #aaa; background: #bbb;}
</style>
</head>
<body>
<h3>Saved Employees</h3>
<table class="emp-table">
<tr>
<th>Name</th>
<th>Department</th>
<th>Date Of Birth</th>
</tr>
<tr th:each="employee : ${employees}">
<td th:text="${employee.name}"></td>
<td th:text="${employee.dept}"></td>
<td th:text="${employee.dateOfBirth}"></td>
</tr>
</table>
</form>
<br/>
<a th:href="@{/}">Add new employee</a>
</body>
</html>
Main class
@SpringBootApplication
public class ExampleMain {
public static void main(String[] args) {
SpringApplication.run(ExampleMain.class);
}
}
Running
To try examples, run spring-boot maven plugin (configured in pom.xml of example project below):
mvn spring-boot:run Or run the main method class from IDE.
Output
Accessing http://localhost:8080/ and entering valid values:
On submitting the form:
On entering invalid values and submitting the form:
Example ProjectDependencies and Technologies Used: - Spring Boot 2.0.3.RELEASE
Corresponding Spring Version 5.0.7.RELEASE - spring-boot-starter-web : Starter for building web, including RESTful, applications using Spring
MVC. Uses Tomcat as the default embedded container.
- spring-boot-starter-thymeleaf : Starter for building MVC web applications using Thymeleaf views.
Uses org.thymeleaf:thymeleaf-spring5 version 3.0.9.RELEASE - hibernate-validator 6.0.10.Final: Hibernate's Bean Validation (JSR-380) reference implementation.
- JDK 1.8
- Maven 3.5.4
|