2011-03-07

Spring Validation 3.0.5

  • Spring 3 支援三種驗證方式:
    • DataBinder
      • 每一個需要驗證的 model class 都應該要有一個相對應的 valitator。
      • 對於 reference class 也應該要用獨立的 validator。
      • ValidationUtils 提供一些基本的驗證 method。
        public class PersonValidator implements Validator {
        
         private Validator addressValidator;
        
         private PersonValidator(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;
         }
        
         @Override
         public boolean supports(Class<?> clazz) {
          // just Person
          return Person.class.equals(clazz);
          // Person and subclass
          // return Person.class.isAssignableFrom(clazz);
         }
        
         @Override
         public void validate(Object obj, Errors e) {
          ValidationUtils.rejectIfEmpty(e, "name", "The name is required");
          Person p = (Person) obj;
          if (p.getAge() < 0) {
           e.rejectValue("age", "Too young");
          }
          else if (p.getAge() > 110) {
           e.rejectValue("age", "Too old");
          }
          try {
           e.pushNestedPath("address");
           ValidationUtils.invokeValidator(this.addressValidator,
             p.getAddress(), e);
          }
          finally {
           e.popNestedPath();
          }
         }
        
         public static void main(String[] args) {
          Person target = new Person();
          DataBinder binder = new DataBinder(target);
          binder.setValidator(new PersonValidator(new AddressValidator()));
        
          // bind to the target object
          binder.bind((propertyValues);
        
          // validate the target object
          binder.validate();
        
          // get BindingResult that includes any validation errors
          BindingResult results = binder.getBindingResult();
          System.out.println(results);
         }
        }
    • JSR-303
      • 使用 javax.validation.constraints 裡的 annotation。
        public class PersonForm {
        
            @NotNull
            @Size(max=64)
            private String name;
        
            @Min(0)
            private int age;
        
        }
      • 必須使用以下的 library。
        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>1.0.0.GA</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>4.0.2.GA</version>
        </dependency>
      • 然後使用以下的 bean 去驗證物件。
        <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>
    • @Controller 結合 JSR-303
      • 使用 @Valid 搭配 javax.validation.constraints 裡的 annotation。
        @RequestMapping(method = RequestMethod.POST)
        public String adduser(@Valid @ModelAttribute("cmd") User cmd, BindingResult result) {
            if (result.hasErrors()) {
                return "userForm";
            }
            if (cmd.getId() == null) {
                this.userService.addUser(cmd);
            }
            else {
                this.userService.updateUser(cmd);
            }
            return "redirect:/user/list.do";
        }
      • 也可以使用 @Valid 搭配 Validator interface。
        @InitBinder
        protected void initBinder(WebDataBinder binder) {
            binder.setValidator(new UserValidator());
        }
相關文章

沒有留言:

張貼留言