使用hibernate-validate 校驗參數bean

hibernate-validate是基於jsr303的,

JSR-303原生支持的限制有如下幾種

限制

說明

@Null

限制只能爲null

@NotNull

限制必須不爲null

@AssertFalse

限制必須爲false

@AssertTrue

限制必須爲true

@DecimalMax(value)

限制必須爲一個不大於指定值的數字

@DecimalMin(value)

限制必須爲一個不小於指定值的數字

@Digits(integer,fraction)

限制必須爲一個小數,且整數部分的位數不能超過integer,小數部分的位數不能超過fraction

@Future

限制必須是一個將來的日期

@Max(value)

限制必須爲一個不大於指定值的數字

@Min(value)

限制必須爲一個不小於指定值的數字

@Past

限制必須是一個過去的日期

@Pattern(value)

限制必須符合指定的正則表達式

@Size(max,min)

限制字符長度必須在minmax之間


我們在使用bean校驗時候

1先創建校驗的bean

package com.hlmedicals.app.vo;

import javax.validation.constraints.NotNull;

import org.hibernate.validator.constraints.NotEmpty;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.factory.annotation.Autowired;

import com.hlmedicals.app.annotation.OrgCodeVlidator;

public class DoctorRegisterParamVO {
    @NotEmpty(message = "真實姓名不能爲空")
    private String realName;
    @NotEmpty(message = "身份證號碼不能爲空")
    private String idcard;
    @NotNull(message = "性別不能爲空")
    @Range(min = 0, max = 1,message="參數異常不能註冊,請按規則填寫 0女1男")
    private int sex;
    @NotNull(message = "電話號不能爲空")
    private long mobilePhone;
    @NotEmpty(message = "機構編碼不能爲空")
    @OrgCodeVlidator
    private String orgCode;
    //@NotEmpty(message = "註冊帳號不能爲空")
    private String username;
    //@NotEmpty(message = "密碼不能爲空")
    private String password;
    /**
     * @return the realName
     */
    public String getRealName() {
        return realName;
    }
    /**
     * @param realName the realName to set
     */
    public void setRealName(String realName) {
        this.realName = realName;
    }
    /**
     * @return the idcard
     */
    public String getIdcard() {
        return idcard;
    }
    /**
     * @param idcard the idcard to set
     */
    public void setIdcard(String idcard) {
        this.idcard = idcard;
    }
    
    /**
     * @return the sex
     */
    public int getSex() {
        return sex;
    }
    /**
     * @return the mobilePhone
     */
    public long getMobilePhone() {
        return mobilePhone;
    }
    /**
     * @param mobilePhone the mobilePhone to set
     */
    public void setMobilePhone(long mobilePhone) {
        this.mobilePhone = mobilePhone;
    }
    /**
     * @param sex the sex to set
     */
    public void setSex(int sex) {
        this.sex = sex;
    }
    /**
     * @return the orgCode
     */
    public String getOrgCode() {
        return orgCode;
    }
    /**
     * @param orgCode the orgCode to set
     */
    public void setOrgCode(String orgCode) {
        this.orgCode = orgCode;
    }
    /**
     * @return the username
     */
    public String getUsername() {
        return username;
    }
    /**
     * @param username the username to set
     */
    public void setUsername(String username) {
        this.username = username;
    }
    /**
     * @return the password
     */
    public String getPassword() {
        return password;
    }
    /**
     * @param password the password to set
     */
    public void setPassword(String password) {
        this.password = password;
    }
    
    
}

2.後臺controller處理(用@valid標示要驗證的bean,沒有這個該beab不會被驗證,驗證結果我們放到bindingResult裏,如果有錯誤就相應的返回錯誤信息)

@RequestMapping(value="/doctorRegister",method=RequestMethod.POST)
    public JsonRe doctorRegister(HttpServletRequest req,HttpServletResponse res,@Valid DoctorRegisterParamVO doctorRegister,BindingResult bindingResult){

       JsonRe jsonRe=new JsonRe();
        
        if(bindingResult.hasErrors()) {  
            List<FieldError> list = bindingResult.getFieldErrors();  
            for (FieldError fieldError : list) {  
                System.out.println(fieldError.getDefaultMessage());  
                jsonRe.setMessage(fieldError.getDefaultMessage());
                break;
            }  
            jsonRe.setCode(202106);
            return  jsonRe;
        }

3.注意

使用hibernate validator出現上面的錯誤, 需要 注意

@NotNull 和 @NotEmpty  和@NotBlank 區別

@NotEmpty 用在集合類上面
@NotBlank 用在String上面
@NotNull    用在基本類型上

4.上面有一個自定義的校驗註解@OrgCodeVlidator

具體實現

package com.hlmedicals.app.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import javax.validation.Constraint;
import javax.validation.Payload;



@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(validatedBy={OrgCodeVlidatorImpl.class})
public @interface OrgCodeVlidator {

    String message() default "請填寫正確的機構編碼";   // 約束註解驗證時的輸出消息
    
    Class<?>[] groups() default {};  
     
    Class<? extends Payload>[] payload() default {};  
}

上面代碼指出了約束校驗指定的類(我們該校驗主要是看該值是否在數據庫中,)


package com.hlmedicals.app.annotation;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.hlmedicals.app.service.HisDepartService;


public class OrgCodeVlidatorImpl implements ConstraintValidator<OrgCodeVlidator, String>{

    @Autowired
    private HisDepartService hisDepartService;
    
    @Override
    public void initialize(OrgCodeVlidator arg0) {
        // TODO Auto-generated method stub
        
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
         if(value==null || value.length()<=0){  
                return false;  
            }else{  
                try {  
                    return hisDepartService.exists(value);
                } catch (Exception e) {  
                    return false;  
                }  
            }  
    }

}

這樣校驗就完成了。


5.驗證工具


  1. package validation.util;  
  2.   
  3. import java.util.Set;  
  4.   
  5. import javax.validation.ConstraintViolation;  
  6. import javax.validation.Validation;  
  7. //import javax.validation.ValidationException;  
  8. import javax.validation.Validator;  
  9. import javax.validation.ValidatorFactory;  
  10. import javax.xml.bind.ValidationException;  
  11.   
  12. /**  
  13.  * @ClassName: VlidationUtil 
  14.  * @Description: 校驗工具類  
  15.  * @author zhangyy  
  16.  * @date 2015-7-31 上午10:28:48   
  17.  */  
  18. public class VlidationUtil {  
  19.   
  20.     private static Validator validator;  
  21.       
  22.     static {  
  23.         ValidatorFactory vf = Validation.buildDefaultValidatorFactory();  
  24.         validator = vf.getValidator();  
  25.     }  
  26.       
  27.   
  28.     /** 
  29.      * @throws ValidationException  
  30.      * @throws ValidationException   
  31.      * @Description: 校驗方法 
  32.      * @param t 將要校驗的對象 
  33.      * @throws ValidationException  
  34.      * void 
  35.      * @throws  
  36.      */   
  37.     public static <T> void validate(T t) throws ValidationException{  
  38.         Set<ConstraintViolation<T>> set =  validator.validate(t);  
  39.         if(set.size()>0){  
  40.             StringBuilder validateError = new StringBuilder();  
  41.             for(ConstraintViolation<T> val : set){  
  42.                 validateError.append(val.getMessage() + " ;");  
  43.             }  
  44.             throw new ValidationException(validateError.toString());              
  45.         }  
  46.     }  
  47.       


6.注意: 以上的需要依賴其他的類庫,下面是maven的依賴(該步驟不能忘記哦)

  1.  <dependency>  
  2.     <groupId>javax.validation</groupId>  
  3.       <artifactId>validation-api</artifactId>  
  4.       <version>1.1.0.Final</version>          
  5. </dependency>  
  6. <dependency>  
  7.        <groupId>org.ow2.util.bundles</groupId>  
  8.      <artifactId>hibernate-validator-4.3.1.Final</artifactId>  
  9.      <version>1.0.0</version>  
  10. </dependency> 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章