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);
}
}
答案 0 :(得分:4)
您需要注册MethodValidationPostProcessor bean以启动方法级别验证注释
委托JSR-303提供程序执行方法级别 对注释方法进行验证。
@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();
}