Validate request data in Spring MVC with Bean Validation

When building any application, it is necessary to handle all possible behaviors when users use our application. One of the cases you will often face when working with Spring MVC applications is that the request data that the user transmits will not correct the expectation so that our application can handle. To avoid these situations, you can use Bean Validation with Spring MVC to prevent such data requests. How is it in details? Let’s find out in this tutorial!

First, I will create a new Spring Boot project with Web Starter dependency for example:

Validate request data in Spring MVC with Bean Validation

Now I will create a new controller with a simple request like this:

Validating the data type of the request parameter “id” in the above example, by defaults, Spring MVC handles already:

Validate request data in Spring MVC with Bean Validation

In the above request, I pass the value to the request parameter id as “Khanh” but the data type of this parameter must be Integer so Spring MVC will respond to the error message.

But in case, we need the value of the request parameter id from users must be greater than or equal to 10 for example, Spring MVC by default does not help us with this. In that case, we can use the code to do this, for example:

or use Java’s Bean Validation as follows:

In the above code, I used the @Min annotation of the Java Bean Validation to declare the constraint for the value of the request parameter id must be greater than or equal to 10 and it is mandatory that you declare the @Validated annotation of Spring.

If the request with the value of the request parameter id is greater than 10, the result will look like this:

Validate request data in Spring MVC with Bean Validation

Similar to requests with request parameters, if your application uses path variable:

then you can also use Java Bean Validation with @Validated annotation of Spring as follows:

Result:

Validate request data in Spring MVC with Bean Validation

For requests that request data in the body such as a POST request, we can also apply Bean Validation to the object that holds the information of the request data.

For example, I have a POST request that transmits student information:

with the student information defined using Bean Validation as follows:

With the above definition, I want the student information to have name and age must be greater than or equal to 18.

To enable Bean Validation in Spring MVC with requests that data is in the body, we will use @Valid annotation of Bean Validation as follows:

The result if I request the invalid request will be as follows:

Validate request data in Spring MVC with Bean Validation

Add Comment