在 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;