Is it possible to validate @RequestParam in Spring MVC REST endpoint?

java, spring, spring-mvc

Solution

Seems it is possible, using `@Validated`.

Here's an example.

Based on OP's question, this should work:

@RestController
@Validated
public class MyController {

  @GetMapping(value="/user/{email}")
  public @ResponseBody IDto getUser(@NotNull @Email @PathVariable String validEmail) {
    return userManagementService.findUserByEmail(validEmail);
  }
 
}

In plain Spring implementations, it may be required to manually register the validator bean:

@Bean
public MethodValidationPostProcessor methodValidationPostProcessor() {
    return new MethodValidationPostProcessor();
}

Problem

In Jersey 2 it is possible to do this: ``` @GET @PATH("user/{email}") public IDto getUser(@NotNull @Email @PathParam("email") String validEmail) { return userManagementService.findUserByEmail(validEmail); } ``` But I cannot make something similar to work in Spring MVC, it seems that the validation is only done when providing an object in @RequestBody or using an SpringMVC Form, for example the following won't work: ``` @RequestMapping(value="/user/{email}", method = RequestMethod.GET) public @ResponseBody IDto getUser(@NotNull @Email @PathVariable String validEmail) { return userManagementService.findUserByEmail(validEmail); } ``` There are other similar questions, but those seem to be oriented to Spring MVC UI applications, in my case it is only a REST API which returns JSON response so I don't have any View to map/bind to the controller.

Original source