As you have learned, in web-based applications, a client can communicate with the server. It means that a client can request data from a server as well as send data to it. The question is: what if a user sends data that violates the business logic of the application? For example, the user can specify a negative age or empty name while filling a registration form. As it could lead to unexpected errors, we need to prevent a situation where a user sends data that violates specified constraints. In cases like that, we can use annotations from the javax.validation package together with Spring Boot annotations.
Here's an example. Imagine you are creating a web application for special agents registration, so now users can send data to the server using the POST HTTP request method with a request body that contains data about special agents:
{
"name": "James",
"surname": "Bond",
"code": "007",
"status": "special agent",
"age": 51
}
Data in the request body represents a POJO class SpecialAgent:
public class SpecialAgent {
private String name;
private String surname;
private String code;
private String status;
private int age;
// getters and setters
}
Now we can set constraints for the fields of the SpecialAgent class using annotations from the javax.validation package.
To start using this package in your Spring Boot application, you need to add a particular dependency.
implementation 'org.springframework.boot:spring-boot-starter-validation'
If you prefer using Maven to Gradle, you can check out the dependency here.
@NotNull annotation is one of the most popular constraint annotations, and it declares that a field cannot be null.
All constraint annotations should be placed on top of the data class fields.
Let's annotate a special agent's name with @NotNull:
@NotNull
private String name;
Now special agent's data that we will send to the server should contain a field name and should not be null. Besides @NotNull annotation, we can use @NotEmpty and @NotBlank annotations. @NotEmpty annotation declares that an annotated field should not be null**,** and the length of the field value should be greater than 0. @NotBlank declares that annotated field value should ****not be empty after trimming. Let's have a look at some examples:
@NotEmpty
private String motto;
@NotBlank
private String status;
The values of the motto and status fields cannot be null and cannot be empty. However, motto value can be equal to " " unlike status, which trimmed value cannot be empty.
The next useful constraints are provided by @Size annotation. This annotation has "min = " and "max = " parameters that specify the boundaries of the field ****(constrain the length).