JSR - 349 bean validation for Spring @RestController with Spring Boot

Viewed 4516

I am using Spring Boot 1.5.2.RELEASE and not able to incorporate JSR - 349 ( bean validation 1.1 ) for @RequestParam & @PathVariable at method itself.

For POST requests, if method parameter is a Java POJO then annotating that parameter with @Valid is working fine but annotating @RequestParam & @PathVariable with something like @NotEmpty, @Email not working.

I have annotated controller class with Spring's @Validated

There are lots of questions on SO and I have commented on this answer that its not working for me.

Spring Boot includes - validation-api-1.1.0.Final.jar and hibernate-validator-5.3.4.Final.jar .

Am I missing anything?

Example code ,

@RequestMapping(method = RequestMethod.GET, value = "/testValidated", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseBean<String> testValidated(@Email @NotEmpty @RequestParam("email") String email) {
    ResponseBean<String> response = new ResponseBean<>();
    response.setResponse(Constants.SUCCESS);
    response.setMessage("testValidated");
    logger.error("Validator Not called");
    return response; 
}

Below handler is never called when I send empty values or not well formed email address for email & control always goes to with in testValidated method.

@ExceptionHandler(ConstraintViolationException.class)
@ResponseBody
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ResponseBean handle(ConstraintViolationException exception) {

    StringBuilder messages = new StringBuilder();
    ResponseBean response = new ResponseBean();

    exception.getConstraintViolations().forEach(entry -> messages.append(entry.getMessage() + "\n"));

    response.setResponse(Constants.FAILURE);
    response.setErrorcode(Constants.ERROR_CODE_BAD_REQUEST);
    response.setMessage(messages.toString());
    return response;
}

ResponseBean<T> is my application specific class.

2 Answers
Related