Expand Authors Top

If you have a few years of experience in the Java ecosystem and you’d like to share that with the community, have a look at our Contribution Guidelines.

Expanded Audience – Frontegg – Security (partner)
announcement - icon User management is very complex, when implemented properly. No surprise here.

Not having to roll all of that out manually, but instead integrating a mature, fully-fledged solution - yeah, that makes a lot of sense.
That's basically what Frontegg is - User Management for your application. It's focused on making your app scalable, secure and enjoyable for your users.
From signup to authentication, it supports simple scenarios all the way to complex and custom application logic.

Have a look:

>> Elegant User Management, Tailor-made for B2B SaaS

November Discount Launch 2022 – Top
We’re finally running a Black Friday launch. All Courses are 30% off until tomorrow:

>> GET ACCESS NOW

November Discount Launch 2022 – TEMP TOP (NPI)
We’re finally running a Black Friday launch. All Courses are 30% off until tomorrow:

>> GET ACCESS NOW

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>6.0.10.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 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, 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 getNameOfDayByNumber(@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 getNameOfDayByNumber(@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 javax.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 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 learned how to validate request parameters and path variables in Spring applications.

As always, all source code is available on GitHub.

November Discount Launch 2022 – Bottom
We’re finally running a Black Friday launch. All Courses are 30% off until tomorrow:

>> GET ACCESS NOW

Generic footer banner
4 Comments
Oldest
Newest
Inline Feedbacks
View all comments
Comments are closed on this article!