在 SpringBoot 开发 web 项目的时候, 表单参数验证, 常用 Hibernate Validator
需要在参数类的属性上添加注解 @NotNull , @Max, @Min 等, 然后再 Controller 方法的请求参数前添加注解 @Valid 就行了, 就可以进行参数自动验证了
然而, 在某些时候我们需要手动发起验证, 可以参考下面这个工具类
public class PropertyValidateUtil {
private static final Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
public static <T> void validate(T object) {
Set<ConstraintViolation<T>> constraintViolationSet = validator.validate(object, Default.class);
if(constraintViolationSet.size() == 0) {
return;
}
StringBuffer message = new StringBuffer("");
for (ConstraintViolation<T> constraintViolation : constraintViolationSet) {
String prefix = message.toString().equals("") ? "" : ", ";
message.append(prefix).append(constraintViolation.getPropertyPath().toString()).append(" ").append(constraintViolation.getMessage());
}
throw new CustomException(ResultEnum.PARAMETER_VALIDATE_FAIL, message.toString());
}
public static <T> void validate(T object, Class<?>... groups) {
Set<ConstraintViolation<T>> constraintViolationSet = validator.validate(object, groups);
if(constraintViolationSet.size() == 0) {
return;
}
StringBuffer message = new StringBuffer("");
for (ConstraintViolation<T> constraintViolation : constraintViolationSet) {
String prefix = message.toString().equals("") ? "" : ", ";
message.append(prefix).append(constraintViolation.getPropertyPath().toString()).append(" ").append(constraintViolation.getMessage());
}
throw new CustomException(ResultEnum.PARAMETER_VALIDATE_FAIL, message.toString());
}
}
group 可以创建几个接口类, 用于标记 Bean 中的不同组验证的属性, 例如:
@NotBlank(groups = {ValidateGroupOne.class})
private String provinceMdmCode;