Generic Top

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE

1. Introduction

In this tutorial, we'll take a look at 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 validation of other types, refer to our tutorials about Java Bean Validation and method constraints or learn how to create your 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>6.0.10.Final</version>
</dependency>

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

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

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 is 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();
    }
    // ...
}

Any error during path or request validation in Spring results by default in an HTTP 500 response. In this tutorial we use a custom implementation of ControllerAdvice to handle this kind of errors in a more readable way and return HTTP 400 for any bad request. You 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 getNameOfDayByNumber(@RequestParam Integer dayOfWeek) {
    // ...
}

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

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

Any request that does not match these conditions will return 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 javax.validation.constraints package to validate a @PathVariable.

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

@GetMapping("/valid-name/{name}")
public void createUsername(@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've learned how to validate both request parameters and path variables in Spring applications.

As always all source code is available on GitHub.

Generic bottom

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE
newest oldest most voted
Notify of
Vivek D More
Guest

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

Should be

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

Eric Martin
Member
Eric Martin

Thanks! Fixed.

Noiran
Guest
Noiran

Hi Eugen,

Thanks for the tutorial. I have a question, is it possible to override the response produced (the 500 HTTP status code and the response body)? If it is, could you please elaborate how? Thanks in advance.

Eric Martin
Member
Eric Martin
Comments are closed on this article!