Java Bean Validation

  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[] payload() default {};
}
  1. 定义校验注解处理器
public class CheckStartEndTimeValidatorHandler implements ConstraintValidator {

  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)