HV000183: Unable to load ‘javax.el.ExpressionFactory'. Check that you have the EL dependencies on the classpath, or use ParameterMessageInterpolator instead
可以通过Validator对Bean进行数据校验
1 2 3 4 5 6 7 8 9 10 11 12
@Test public void test6() { FetchWordResultDTO fetchWordResultDTO = new FetchWordResultDTO(); ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); Set<ConstraintViolation<FetchWordResultDTO>> results = validator.validate(fetchWordResultDTO); for (ConstraintViolation<FetchWordResultDTO> result : results) { System.out.println(result.getPropertyPath()); System.out.println(result.getMessage()); System.out.println(result.getInvalidValue()); } }
空检查 @Null 验证对象是否为null @NotNull 验证对象是否不为null, 无法查检长度为0的字符串 @NotBlank 检查约束字符串是不是Null还有被Trim的长度是否大于0,只对字符串,且会去掉前后空格. @NotEmpty 检查约束元素是否为NULL或者是EMPTY. Booelan检查 @AssertTrue 验证 Boolean 对象是否为 true @AssertFalse 验证 Boolean 对象是否为 false 长度检查 @Size(min=, max=) 验证对象(Array,Collection,Map,String)长度是否在给定的范围之内 @Length(min=, max=) Validates that the annotated string is between min and max included. 日期检查 @Past 验证 Date 和 Calendar 对象是否在当前时间之前 @Future 验证 Date 和 Calendar 对象是否在当前时间之后 @Pattern 验证 String 对象是否符合正则表达式的规则 @Past and @PastOrPresent – validate that a date value is in the past or the past including the present; can be applied to date types including those added in Java 8 @Future and @FutureOrPresent – validates that a date value is in the future, or in the future including the present 数值检查,建议使用在Stirng,Integer类型,不建议使用在int类型上,因为表单值为“”时无法转换为int,但可以转换为Stirng为"",Integer为null @Min 验证 Number 和 String 对象是否大等于指定的值 @Max 验证 Number 和 String 对象是否小等于指定的值 @DecimalMax 被标注的值必须不大于约束中指定的最大值. 这个约束的参数是一个通过BigDecimal定义的最大值的字符串表示.小数存在精度 @DecimalMin 被标注的值必须不小于约束中指定的最小值. 这个约束的参数是一个通过BigDecimal定义的最小值的字符串表示.小数存在精度 @Digits 验证 Number 和 String 的构成是否合法 @Digits(integer=,fraction=) 验证字符串是否是符合指定格式的数字,interger指定整数精度,fraction指定小数精度。 @Positive and @PositiveOrZero – apply to numeric values and validate that they are strictly positive, or positive including 0 @Negative and @NegativeOrZero – apply to numeric values and validate that they are strictly negative, or negative including 0 @Range(min=, max=) 检查数字是否介于min和max之间. @Range(min=10000,max=50000,message="range.bean.wage") private BigDecimal wage; @Valid 递归的对关联对象进行校验, 如果关联对象是个集合或者数组,那么对其中的元素进行递归校验,如果是一个map,则对其中的值部分进行校验.(是否进行递归验证) @CreditCardNumber信用卡验证 @Email 验证是否是邮件地址,如果为null,不进行验证,算通过验证。 @ScriptAssert(lang= ,script=, alias=) @URL(protocol=,host=, port=,regexp=, flags=) // 参考 https://www.cnblogs.com/yangzhilong/p/3724967.html
Validation in Spring Boot
利用@Valid对数据做优雅的校验
校验异常会抛出MethodArgumentNotValidException,然后可以Spring的机制定义全局异常处理器。 Demo of Controller:
1 2 3 4
@PostMapping("/storeFetchWordResult") public R storeFetchWordResult(@RequestBody @Valid FetchWordResultDTO fetchWordResultDTO) { // do something }
@Constraint(validatedBy = ConsistentDateParameterValidator.class) @Target({ METHOD, CONSTRUCTOR }) @Retention(RUNTIME) @Documented public @interface ConsistentDateParameters { String message() default "End date must be after begin date and both must be in the future"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }
@SupportedValidationTarget(ValidationTarget.PARAMETERS) public class ConsistentDateParameterValidator implements ConstraintValidator<ConsistentDateParameters, Object[]> { @Override public boolean isValid( Object[] value, ConstraintValidatorContext context) { if (value[0] == null || value[1] == null) { return true; } if (!(value[0] instanceof LocalDate) || !(value[1] instanceof LocalDate)) { throw new IllegalArgumentException( "Illegal method signature, expected two parameters of type LocalDate."); } return ((LocalDate) value[0]).isAfter(LocalDate.now()) && ((LocalDate) value[0]).isBefore((LocalDate) value[1]); } }
自定义返回值的校验注解
比如要校验某个复杂的对象Reservation:
1 2 3 4 5 6 7
public class ReservationManagement { @ValidReservation public Reservation getReservationsById(int id) { return null; } }
自定义注解,注意注解的范围可以是构造器CONSTRUCTOR:
1 2 3 4 5 6 7 8 9 10 11 12
@Constraint(validatedBy = ValidReservationValidator.class) @Target({ METHOD, CONSTRUCTOR }) @Retention(RUNTIME) @Documented public @interface ValidReservation { String message() default "End date must be after begin date " + "and both must be in the future, room number must be bigger than 0"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }