对于POST请求,如果method参数是Java POJO,则使用@Valid注释该参数工作正常但注释@RequestParam& @PathVariable与@NotEmpty,@ Email无法正常工作.
我有Spring的@Validated注释控制器类
关于SO有很多问题,我在this answer评论说它不适用于我.
Spring Boot包括 – validation-api-1.1.0.Final.jar和hibernate-validator-5.3.4.Final.jar.
我错过了什么吗?
示例代码,
@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; }
当我发送空值或电子邮件地址不完整的电子邮件地址时,永远不会调用下面的处理程序.控制总是在testValidated方法中使用.
@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>是我的应用程序特定类.
解决方法
最后,this article帮了很多忙.
我分两步解决了问题,
1.在我的配置中添加了以下bean – 没有这些bean,没有任何作用.
@Bean public MethodValidationPostProcessor methodValidationPostProcessor() { MethodValidationPostProcessor mvProcessor = new MethodValidationPostProcessor(); mvProcessor.setValidator(validator()); return mvProcessor; } @Bean public LocalValidatorfactorybean validator() { LocalValidatorfactorybean validator = new LocalValidatorfactorybean(); validator.setProviderClass(HibernateValidator.class); validator.afterPropertiesSet(); return validator; }
2.在我的控制器上放置Spring的@Validated注释,如下所示,
@RestController @RequestMapping("/...") @Validated public class MyRestController { }
验证是 – org.springframework.validation.annotation.Validated
此设置不影响同一控制器中@RequestBody验证的@Valid注释,并且这些注释继续按原样运行.
所以现在,我可以触发MyRestController类中的方法,如下所示的验证,produces = MediaType.APPLICATION_JSON_VALUE) public ResponseBean<String> testValidated( @Email(message="email RequestParam is not a valid email address") @NotEmpty(message="email RequestParam is empty") @RequestParam("email") String email) { ResponseBean<String> response = new ResponseBean<>(); .... return response; }
我必须在异常处理程序中为异常添加另一个处理程序 – ConstraintViolationException,因为@Validated抛出此异常,而@Valid抛出MethodArgumentNotValidException