javax bean验证不适用于方法参数

sur*_*rya 5 java spring hibernate-validator bean-validation spring-boot

javax验证不适用于方法参数。这是测试代码,并且javax验证均不适用于方法参数。

@RequestMapping(value = "/{id}", method = RequestMethod.PUT, params = "action=testAction")
public Test update(
        @Size(min = 1) @RequestBody List<String> ids,
        @Min(3) @PathVariable String name) {
    return doSomething(ids, name);
}
Run Code Online (Sandbox Code Playgroud)

但是我有很好的类级别验证...

@RequestMapping(method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)
public RoleType create (@RequestBody @Validated(FieldType.class) User user) {
    ...
}
Run Code Online (Sandbox Code Playgroud)

@Size(min = 2, max = 10, groups = { FieldType.class }, message = "Invalid user code")
 public String getId() {
    return _id  ;
}
Run Code Online (Sandbox Code Playgroud)

-解决方案-

按照接受的答案执行所有步骤。另一个附加功能是在课堂上添加注释

@Validated
class UserController
{
   @RequestMapping(value = "/{id}", method = RequestMethod.PUT, params ="action=testAction")
   public Test update(@Size(min = 1) @RequestBody List<String> ids,@Min(3) @PathVariable String name) {
    return doSomething(ids, name);
}
}
Run Code Online (Sandbox Code Playgroud)

kuh*_*yan 9

你需要注册MethodValidationPostProcessor bean 来踢方法级别的验证注解

委托给 JSR-303 提供者以对带注释的方法执行方法级验证。

  @Bean
     public MethodValidationPostProcessor methodValidationPostProcessor() {
          return new MethodValidationPostProcessor();
     }
Run Code Online (Sandbox Code Playgroud)

然后,

@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
public Test update(
        @Size(min = 1) @RequestBody List<String> ids,
        @Min(3) @PathVariable("id") String name) {
    return doSomething(ids, name);
}
Run Code Online (Sandbox Code Playgroud)

如果你想处理验证异常

@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();
 }
Run Code Online (Sandbox Code Playgroud)

  • 感谢您提供详尽的答案,我忘记添加该 bean 配置,另一件事是我忘记在类级别添加 @validated 注释..现在它可以工作了。 (3认同)