`
thaIm
  • 浏览: 91595 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Spring --- Validation

阅读更多
一) 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模块的介绍中再详细介绍。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics