代码
自定义注解
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 {
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 Map validate(T obj){
Map errorMap = null;
Set> set = validator.validate(obj,Default.class);
if(set != null && set.size() >0 ){
errorMap = new HashMap();
String property = null;
for(ConstraintViolation 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 String validateThrowE(T obj){
Map errorMap= validate(obj);
List list=new ArrayList();
if(StringUtil.isNotEmpty(errorMap)){//有错误
Set 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)