引用的jar
org.hibernate hibernate-validator 5.4.1.Final javax.validation validation-api 1.1.0.Final org.jboss.logging jboss-logging 3.3.0.Final com.fasterxml classmate 1.0.0 javax.el javax.el-api 2.2.4 org.glassfish.web javax.el 2.2.4
xml配置
工具类
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 staticMap 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; } }
测试
demo类
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;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;//密码 public DemoQuery(Integer departmentID, String parentID, String name, Integer code, String remarks, Boolean isActive, Date createDate, String pass) { super(); this.departmentID = departmentID; this.parentID = parentID; this.name = name; this.code = code; this.remarks = remarks; this.isActive = isActive; this.createDate = createDate; this.pass = pass; } 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(); fsre.setPass("11122"); ValidatorUtil.validateThrowE(fsre); } }
输出
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: [密码大小不能超过4] at com.feizhou.common.tools.commonTools.ValidatorUtil.validateThrowE(ValidatorUtil.java:68) at com.feizhou.core.bean.demo.DemoQuery.main(DemoQuery.java:106)
controler测试
@RequestMapping(value = "/demoController/selectList.do") public void selectList(HttpServletResponse response,HttpServletRequest resquest, @Valid DemoQuery demoQuery, BindingResult bindingResult, Model model){//@Valid注解对user进行校验,并将校验结果保存在bindingResult中,// @Valid后面必须紧跟indingResult/Errors类型,中间没有其他参数,它们总是成对出现。 if(bindingResult.hasErrors()){ Listerrors=bindingResult.getAllErrors(); System.out.println("开始打印错误信息:"+errors); for (ObjectError objectError : errors) { System.out.println("Code:"+objectError.getCode()); System.out.println("DefaultMessage:"+objectError.getDefaultMessage()); System.out.println("ObjectName():"+objectError.getObjectName()); System.out.println("Arguments:"+objectError.getArguments()); } } System.out.println("代码继续走下去"); }
结果
2018-07-19 14:03:04,077 [http-bio-8080-exec-6] DEBUG [org.springframework.web.servlet.DispatcherServlet] - DispatcherServlet with name 'SpringMVC' processing GET request for [/demoController/selectList.do] 2018-07-19 14:03:04,077 [http-bio-8080-exec-6] DEBUG [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping] - Looking up handler method for path /demoController/selectList.do 2018-07-19 14:03:04,077 [http-bio-8080-exec-6] DEBUG [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping] - Returning handler method [public void com.feizhou.core.controller.DemoController.selectList(javax.servlet.http.HttpServletResponse,javax.servlet.http.HttpServletRequest,com.feizhou.core.bean.demo.DemoQuery,org.springframework.validation.BindingResult,org.springframework.ui.Model)] 2018-07-19 14:03:04,077 [http-bio-8080-exec-6] DEBUG [org.springframework.beans.factory.support.DefaultListableBeanFactory] - Returning cached instance of singleton bean 'demoController' 2018-07-19 14:03:04,078 [http-bio-8080-exec-6] DEBUG [org.springframework.web.servlet.DispatcherServlet] - Last-Modified value for [/demoController/selectList.do] is: -1 开始打印错误信息:[Field error in object 'demoQuery' on field 'pass': rejected value [null]; codes [NotNull.demoQuery.pass,NotNull.pass,NotNull.java.lang.String,NotNull]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [demoQuery.pass,pass]; arguments []; default message [pass]]; default message [密码不能为空]]Code:NotNullDefaultMessage:密码不能为空ObjectName():demoQueryArguments:[Ljava.lang.Object;@3d5ae7c9代码继续走下去2018-07-19 14:03:04,080 [http-bio-8080-exec-6] DEBUG [org.springframework.web.servlet.DispatcherServlet] - Null ModelAndView returned to DispatcherServlet with name 'SpringMVC': assuming HandlerAdapter completed request handling 2018-07-19 14:03:04,080 [http-bio-8080-exec-6] DEBUG [org.springframework.web.servlet.DispatcherServlet] - Successfully completed request