This short post demonstrates how to set up and use JSR-303 Validation for the arguments in Spring MVC request mapping methods for path variable and request parameter arguments. I am using Spring Boot v1.2.5 with Maven 3.
I. MethodValidationPostProcessor
The only configuration needed is adding the MethodValidationPostProcessor (javadoc) bean to the Spring configuration, e.g.
@Bean public MethodValidationPostProcessor methodValidationPostProcessor() { return new MethodValidationPostProcessor(); }
II Add validation to controller request mapping method
First, add the @Validate annotation to the controller class as follows:
@RestController @Validated public class HelloController { ...
Then add any JSR-303 validation annotation to a request mapping method arguments:
@RequestMapping("/hi/{name}") public String sayHi(@Size(max = 10, min = 3, message = "name should have between 3 and 10 characters") @PathVariable("name") String name) { return "Hi " + name; }
The example codes above shows how to validate a value in the request path marked by @PathVariable. You can do the same with @RequestParam
III Validation exception handling
A ConstraintViolationException will be thrown if the size of the path variable is not within 3 to 10 characters. You may need to catch this exception and process it using a Spring MVC exception handler, for example to return the error messages in the response:
@ExceptionHandler(value = { ConstraintViolationException.class }) @ResponseStatus(value = HttpStatus.BAD_REQUEST) public String handleResourceNotFoundException(ConstraintViolationException e) { Set<ConstraintViolation<?>> violations = e.getConstraintViolations(); StringBuilder strBuilder = new StringBuilder(); for (ConstraintViolation<?> violation : violations ) { strBuilder.append(violation.getMessage() + "\n"); } return strBuilder.toString(); }