javax bean验证不处理方法参数
作者:互联网
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);
}
但我有类级别的验证,完美的工作……
@RequestMapping(method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)
public RoleType create (@RequestBody @Validated(FieldType.class) User user) {
...
}
和
@Size(min = 2, max = 10, groups = { FieldType.class }, message = "Invalid user code")
public String getId() {
return _id ;
}
– 解决方案 –
根据接受的答案遵循所有步骤.
而另一个补充是在班级上的宣布
@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);
}
}
解决方法:
你需要注册MethodValidationPostProcessor bean来踢方法级别验证注释
delegates to a JSR-303 provider for performing method-level
validation on annotated methods.
@Bean
public MethodValidationPostProcessor methodValidationPostProcessor() {
return new MethodValidationPostProcessor();
}
然后,
@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);
}
如果要处理验证异常
@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();
}
标签:java,spring,bean-validation,spring-boot-2,hibernate-validator 来源: https://codeday.me/bug/20190623/1267228.html