我想使用bean验证的代码:
@Inject
private ValidatorFactory validatorFactory;
....
public Response create(@Context HttpServletRequest request) {
...
Set<ConstraintViolation<UserDTO>> validate = validatorFactory.getValidator().validate(userDTO);
validate.forEach(error-> System.err.println(error.getMessage()));
if(validate.size() > 0){
throw new ValidationException("userDTO is not valid!");
}
...
}
public Response update(@Context HttpServletRequest request) {
Set<ConstraintViolation<UserDTO>> validate = validatorFactory.getValidator().validate(userDTO);
validate.forEach(error-> System.err.println(error.getMessage()));
if(validate.size() > 0){
throw new ValidationException("userDTO is not valid!");
}
...
}
UserDTO:
public class UserDTO {
private Integer id;
private String userName;
@NotNull(message = "is missing")
private String locked;
@Email(message = "email is not valid")
private String email;
@NotNull(message = "countryCode is missing")
private String countryCode;
...getters-setters more variables...
}
所以我有一个帖子Http方法,我想创建一个用户...如果缺少国家代码或锁定确定或如果电子邮件无效,则bean验证正常工作...但是当我想更新例如电子邮件时验证也在整个dto类上运行...所以问题是我可以如何配置每次都不在每个变量上运行?
答案 0 :(得分:1)
您应该使用Validator::validateProperty
来检查特定属性。如果有多个媒体资源,您也可以将其分组并通过Validator::validate
进行检查(有关教程,请参阅here)。