春豆验证@Valid处理
我使用以下方法使用Bean Validation 1.2创建了一个Spring MVC REST服务:
@RequestMapping(value = "/valid")
public String validatedMethod(@Valid ValidObject object) {
}
如果对象无效,Tomcat 会通知我,并且我的永远不会被调用。The request sent by the client was syntactically incorrect.
validatedMethod
如何获取在 Bean 中定义的消息?我应该使用一些过滤器还是拦截器?ValidObject
我知道我可以像下面这样重写,从注入中获取s的集合,但上面似乎更整洁...ConstraintViolation
Validator
@RequestMapping(value = "/valid")
public String validatedMethod(ValidObject object) {
Set<ConstraintViolation<ValidObject>> constraintViolations = validator
.validate(object);
if (constraintViolations.isEmpty()) {
return "valid";
} else {
final StringBuilder message = new StringBuilder();
constraintViolations.forEach((action) -> {
message.append(action.getPropertyPath());
message.append(": ");
message.append(action.getMessage());
});
return message.toString();
}
}