美文网首页
Java Bean Validation

Java Bean Validation

作者: 赛亚人之神 | 来源:发表于2019-10-12 17:06 被阅读0次
    1. 定义校验注解
    @Documented
    @Retention(RetentionPolicy.RUNTIME)
    @Target({ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.TYPE})
    @Constraint(validatedBy = CheckStartEndTimeValidatorHandler.class)
    public @interface CheckStartEndTimeValidator {
    
      String startTime() default "startTime";
      String endTime() default "endTime";
    
      String message() default "开始时间不能大于结束时间!";
    
      Class<?>[] groups() default {};
    
      Class<? extends Payload>[] payload() default {};
    }
    
    1. 定义校验注解处理器
    public class CheckStartEndTimeValidatorHandler implements ConstraintValidator<CheckStartEndTimeValidator, Object> {
    
      private String startTime;
      private String endTime;
    
      @Override
      public void initialize(CheckStartEndTimeValidator constraintAnnotation) {
        this.startTime = constraintAnnotation.startTime();
        this.endTime = constraintAnnotation.endTime();
    
      }
    
      @Override
      public boolean isValid(Object value, ConstraintValidatorContext context) {
        if (value == null) {
          return true;
        }
    
        BeanWrapper beanWrapper = new BeanWrapperImpl(value);
        Object start = beanWrapper.getPropertyValue(startTime);
        Object end = beanWrapper.getPropertyValue(endTime);
    
        if (null == start || end == null) {
          return true;
        }
    
        int result = ((Date) end).compareTo((Date) start);
    
        if (result >= 0) {
          return true;
        }
    
        return false;
      }
    }
    
    1. 定义要校验的 model
    @Data
    @CheckStartEndTimeValidator(startTime = "createStartTime", endTime = "createEndTime")
    public class TestModel {
    
      private String name;
    
      private Date createStartTime;
      private Date createEndTime;
    }
    
    1. controller 中使用 @Validated 校验方法
      @RequestMapping("v")
      public void validator(@Validated @RequestBody TestModel model) {
    
      }
    

    相关文章

      网友评论

          本文标题:Java Bean Validation

          本文链接:https://www.haomeiwen.com/subject/tsscuctx.html