Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Introduction

In this tutorial, we’ll learn how to validate HTTP request parameters and path variables in Spring MVC.

Specifically, we’ll validate String and Number parameters with JSR 303 annotations.

To explore the validation of other types, we can refer to our tutorials about Java Bean Validation and method constraints, or we can learn how to create our own validator.

2. Configuration

To use the Java Validation API, we have to add a JSR 303 implementation, such as hibernate-validator:

<dependency>
    <groupId>org.hibernate.validator</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>8.0.1.Final</version>
</dependency>

We also have to enable validation for both request parameters and path variables in our controllers by adding the @Validated annotation:

@RestController
@RequestMapping("/")
@Validated
public class RequestAndPathVariableValidationController {
    // ...
}

It’s important to note that enabling parameter validation also requires a MethodValidationPostProcessor bean. If we’re using a Spring Boot application, then this bean is auto-configured, as we have the hibernate-validator dependency on our classpath.

Otherwise, in a standard Spring application, we have to add this bean explicitly:

@EnableWebMvc
@Configuration
@ComponentScan("com.baeldung.spring")
public class ClientWebConfigJava implements WebMvcConfigurer {
    @Bean
    public MethodValidationPostProcessor methodValidationPostProcessor() {
        return new MethodValidationPostProcessor();
    }
    // ...
}

By default, any error during path or request validation in Spring results in an HTTP 500 response. In this tutorial, we’ll use a custom implementation of ControllerAdvice to handle these kinds of errors in a more readable way, returning an HTTP 400 for any bad request. We can find the source code of this solution at GitHub.

3. Validating a RequestParam

Let’s consider an example where we pass a numeric weekday into a controller method as a request parameter:

@GetMapping("/name-for-day")
public String getNameOfDayByNumberRequestParam(@RequestParam Integer dayOfWeek) {
    // ...
}

Our goal is to make sure that the value of dayOfWeek is between 1 and 7. To do so, we’ll use the @Min and @Max annotations:

@GetMapping("/name-for-day")
public String getNameOfDayByNumberRequestParam(@RequestParam @Min(1) @Max(7) Integer dayOfWeek) {
    // ...
}

Any request that doesn’t match these conditions will return an HTTP status 400 with a default error message.

If we call http://localhost:8080/name-for-day?dayOfWeek=24, for instance, the response message will be:

getNameOfDayByNumber.dayOfWeek: must be less than or equal to 7

We can change the default message by adding a custom one:

@Max(value = 1, message = “day number has to be less than or equal to 7”)

4. Validating a PathVariable

Just as with @RequestParam, we can use any annotation from the jakarta.validation.constraints package to validate a @PathVariable.

Let’s consider an example where we validate that a String parameter isn’t blank and has a length of less than or equal to 10:

@GetMapping("/valid-name/{name}")
public void validStringRequestParam(@PathVariable("name") @NotBlank @Size(max = 10) String username) {
    // ...
}

Any request with a name parameter longer than 10 characters, for instance, will result in an HTTP 400 error with a message:

createUser.name:size must be between 0 and 10

The default message can be easily overwritten by setting the message parameter in the @Size annotation.

5. Conclusion

In this article, we learned how to validate request parameters and path variables in Spring applications.

As always, all source code is available on GitHub.

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
4 Comments
Oldest
Newest
Inline Feedbacks
View all comments
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.