Spring Web MVC – validate individual request params

This seems to be possible now (tried with Spring 4.1.2), see https://raymondhlee.wordpress.com/2015/08/29/validating-spring-mvc-request-mapping-method-parameters/

Extract from above page:

  1. Add MethodValidationPostProcessor to Spring @Configuration class:

    @Bean
    public MethodValidationPostProcessor methodValidationPostProcessor() {
        return new MethodValidationPostProcessor();
    }
    
  2. Add @Validated to controller class

  3. Use @Size just before @RequestParam

    @RequestMapping("/hi")
    public String sayHi(@Size(max = 10, message = "name should at most 10 characters long") @RequestParam("name") String name) {
        return "Hi " + name;
    

    }

  4. Handle ConstraintViolationException in an @ExceptionHandler method

Leave a Comment