Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@PathVariable Validation in Spring 4

How can i validate my path variable in spring. I want to validate id field, since its only single field i do not want to move to a Pojo

@RestController
public class MyController {
    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public ResponseEntity method_name(@PathVariable String id) {
        /// Some code
    }
}

I tried doing adding validation to the path variable but its still not working

    @RestController
    @Validated
public class MyController {
    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public ResponseEntity method_name(
            @Valid 
            @Nonnull  
            @Size(max = 2, min = 1, message = "name should have between 1 and 10 characters") 
            @PathVariable String id) {
    /// Some code
    }
}
like image 210
R.A.S. Avatar asked Feb 15 '16 07:02

R.A.S.


1 Answers

You need to create a bean in your Spring configuration:

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

You should leave the @Validated annotation on your controller.

And you need an Exceptionhandler in your MyController class to handle theConstraintViolationException :

@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();
    }

After those changes you should see your message when the validation hits.

P.S.: I just tried it with your @Size validation.

like image 181
Patrick Avatar answered Nov 16 '22 00:11

Patrick