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 the validation-api dependency:
<dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>2.0.1.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 { // ... }
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 500 with a default error message.
If we call http://localhost:8080/name-for-day?dayOfWeek=24, for instance, the response message will be:
There was an unexpected error (type=Internal Server Error, status=500). 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 error with a message:
There was an unexpected error (type=Internal Server Error, status=500). 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.