ITeye博客

Spring --- Validation

thaIm · 2012-12-07 15:05 · Spring · 编程语言 · Markdown

一) Validator接口 Spring的Validation功能设计很简单。使用Validator功能即可:

public class Person {
  private String name;
  private int age;
  // the usual getters and setters...
}
public class PersonValidator implements Validator {
  /**
  * This Validator validates just Person instances
  */
  public boolean supports(Class clazz) {
   return Person.class.equals(clazz);
  }
  public void validate(Object obj, Errors e) {
    ValidationUtils.rejectIfEmpty(e, "name", "name.empty");
    Person p = (Person) obj;
    if (p.getAge() < 0) {
      e.rejectValue("age", "negativevalue");
    } else if (p.getAge() > 110) {
      e.rejectValue("age", "too.darn.old");
    }
  }
}

Spring的Validate策略就是一个类(Person)对应一个校验类(PersonValidator)。至于校验类的绑定,可以代码中显式的调用,也可以是采用annotation。个人比较推荐用annotation的方法。而如果在一个类的校验中需要用到另一个类的校验,我们可以这样写:

public class CustomerValidator implements Validator {
  private final Validator addressValidator;
  public CustomerValidator(Validator addressValidator) {
    if (addressValidator == null) {
      throw new IllegalArgumentException(
"The supplied [validator] is required and must not be null.");
    }
    if (!addressValidator.supports(Address.class)) {
      throw new IllegalArgumentException(
"The supplied [validator] must support the validation of [address] instances.");
    }
    this.addressValidator = addressValidator;
}
  /**
  * This Validator validates Customer instances, and any subclasses of Customer too
  */
  public boolean supports(Class clazz) {
    return Customer.class.isAssignableFrom(clazz);
  }
  public void validate(Object target, Errors errors) {
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstName", "field.required");
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "surname", "field.required");
    Customer customer = (Customer) target;
    try {
      errors.pushNestedPath("address");
      ValidationUtils.invokeValidator(this.addressValidator,customer.getAddress(), errors);
    } finally {
      errors.popNestedPath();
    }
  }
}

在CustomerValidator 中就用到了addressValidator。另外对于Errors类,可在Spring MVC模块中结合使用。具体使用方式我们在Spring MVC模块的介绍中再详细介绍。

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。