spring 自定義校驗規則
阿新 • • 發佈:2019-01-08
程式碼
自定義註解
Money
package com.feizhou.common.validator; 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, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Constraint(validatedBy=MoneyValidator.class) public @interface Money { String message() default"不是金額形式"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }
MoneyValidator
package com.feizhou.common.validator; import java.util.regex.Pattern; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; public class MoneyValidator implements ConstraintValidator<Money, Double> { private String moneyReg = "^\\d+(\\.\\d{1,2})?$";//表示金額的正則表示式 private Pattern moneyPattern = Pattern.compile(moneyReg); public void initialize(Money money) { // TODO Auto-generated method stub } public boolean isValid(Double value, ConstraintValidatorContext arg1) { if (value == null) //金額是空的,返回true,是因為如果null,則會有@NotNull進行提示 //如果這裡false的話,那金額是null,@Money中的message也會進行提示 //自己可以嘗試 return true; return moneyPattern.matcher(value.toString()).matches(); } }
測試
package com.feizhou.core.bean.demo; import java.util.Date; import javax.validation.constraints.Max; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; import javax.validation.constraints.Size; import com.feizhou.common.tools.commonTools.ValidatorUtil; import com.feizhou.common.validator.Money; public class DemoQuery { @Max(value=12,message = " 部門id必須小於12") private Integer departmentID;// 部門id @Pattern(regexp = "\\S{6,30}",message = "部門父id必須在6-30之間") private String parentID; // 部門父id @Pattern(regexp = "^((1[3,5,8][0-9])|(14[5,7])|(17[0,6,7,8])|(19[7]))\\d{8}$",message = "錢爸爸使用者名稱輸入錯誤") private String name;//部門名稱 // @Max(value = 100,message = "部門編碼必須小於100") // @Min(value = 18,message = "部門編碼必須大於18") private Integer code;// 部門編碼 // @Size(max = 4,min=1,message = "備註大小不能超過4") @Max(value = 100,message = "備註必須小於100") @Min(value = 18,message = "備註必須大於18") private String remarks;// 備註 private Boolean isActive; // 是否啟用 // @Past(message="建立日期必須小於當前日期") private Date createDate; // 建立日期 @NotNull(message = "密碼不能為空") @Size(max = 4,message = "密碼大小不能超過4") private String pass;//密碼 @NotNull(message="金額不能為空") @Money(message="金額格式不正確") private Double money; public Double getMoney() { return money; } public void setMoney(Double money) { this.money = money; } public String getPass() { return pass; } public void setPass(String pass) { this.pass = pass; } public Integer getDepartmentID() { return departmentID; } public void setDepartmentID(Integer departmentID) { this.departmentID = departmentID; } public String getParentID() { return parentID; } public void setParentID(String parentID) { this.parentID = parentID; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } public String getRemarks() { return remarks; } public void setRemarks(String remarks) { this.remarks = remarks; } public Boolean getIsActive() { return isActive; } public void setIsActive(Boolean isActive) { this.isActive = isActive; } public Date getCreateDate() { return createDate; } public void setCreateDate(Date createDate) { this.createDate = createDate; } @Override public String toString() { return "DemoQuery [departmentID=" + departmentID + ", parentID=" + parentID + ", name=" + name + ", code=" + code + ", remarks=" + remarks + ", isActive=" + isActive + ", createDate=" + createDate + "]"; } public DemoQuery() { super(); } public static void main(String[] args) { DemoQuery fsre=new DemoQuery(); ValidatorUtil.validateThrowE(fsre); } }
驗證的工具類
package com.feizhou.common.tools.commonTools;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.groups.Default;
import com.feizhou.common.exception.MyException;
public class ValidatorUtil {
private static Validator validator = Validation.buildDefaultValidatorFactory()
.getValidator();
/**
*
* @Description (驗證物件的註解)
* @author feizhou
* @Date 2018年7月2日下午5:04:04
* @version 1.0.0
* @param obj
* @return
*/
public static <T> Map<String,StringBuffer> validate(T obj){
Map<String,StringBuffer> errorMap = null;
Set<ConstraintViolation<T>> set = validator.validate(obj,Default.class);
if(set != null && set.size() >0 ){
errorMap = new HashMap<String,StringBuffer>();
String property = null;
for(ConstraintViolation<T> cv : set){
//這裡迴圈獲取錯誤資訊,可以自定義格式
property = cv.getPropertyPath().toString();
if(errorMap.get(property) != null){
errorMap.get(property).append("," + cv.getMessage());
}else{
StringBuffer sb = new StringBuffer();
sb.append(cv.getMessage());
errorMap.put(property, sb);
}
}
}
return errorMap;
}
/**
*
* @Description (檢測物件是否有錯誤,有錯誤丟擲異常)
* @author feizhou
* @Date 2018年7月2日下午1:49:24
* @version 1.0.0
* @param obj
* @return
*/
public static <T> String validateThrowE(T obj){
Map<String,StringBuffer> errorMap= validate(obj);
List<StringBuffer> list=new ArrayList<StringBuffer>();
if(StringUtil.isNotEmpty(errorMap)){//有錯誤
Set<String> keys = errorMap.keySet();
for (String key : keys) {
list.add(errorMap.get(key));
}
}
if(StringUtil.isNotEmpty(list)){
throw new MyException(list.toString());
}
return null;
}
}
結果
log4j:WARN No appenders could be found for logger (org.jboss.logging).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Exception in thread "main" com.feizhou.common.exception.MyException: [金額不能為空, 密碼不能為空]
at com.feizhou.common.tools.commonTools.ValidatorUtil.validateThrowE(ValidatorUtil.java:68)
at com.feizhou.core.bean.demo.DemoQuery.main(DemoQuery.java:106)