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) |
限制字符長度必須在min到max之間 |
我們在使用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.驗證工具
- package validation.util;
- import java.util.Set;
- import javax.validation.ConstraintViolation;
- import javax.validation.Validation;
- //import javax.validation.ValidationException;
- import javax.validation.Validator;
- import javax.validation.ValidatorFactory;
- import javax.xml.bind.ValidationException;
- /**
- * @ClassName: VlidationUtil
- * @Description: 校驗工具類
- * @author zhangyy
- * @date 2015-7-31 上午10:28:48
- */
- public class VlidationUtil {
- private static Validator validator;
- static {
- ValidatorFactory vf = Validation.buildDefaultValidatorFactory();
- validator = vf.getValidator();
- }
- /**
- * @throws ValidationException
- * @throws ValidationException
- * @Description: 校驗方法
- * @param t 將要校驗的對象
- * @throws ValidationException
- * void
- * @throws
- */
- public static <T> void validate(T t) throws ValidationException{
- Set<ConstraintViolation<T>> set = validator.validate(t);
- if(set.size()>0){
- StringBuilder validateError = new StringBuilder();
- for(ConstraintViolation<T> val : set){
- validateError.append(val.getMessage() + " ;");
- }
- throw new ValidationException(validateError.toString());
- }
- }
-
}
6.注意: 以上的需要依賴其他的類庫,下面是maven的依賴(該步驟不能忘記哦)
- <dependency>
- <groupId>javax.validation</groupId>
- <artifactId>validation-api</artifactId>
- <version>1.1.0.Final</version>
- </dependency>
- <dependency>
- <groupId>org.ow2.util.bundles</groupId>
- <artifactId>hibernate-validator-4.3.1.Final</artifactId>
- <version>1.0.0</version>
-
</dependency>