java使用validator进行校验

不管是html页面表单提交的对象数据还是和第三方公司进行接口对接,都需要对接收到的数据进行校验(非空、长度、格式等等)。如果使用if一个个进行校验(字段非常多),这是让人崩溃的过程。幸好jdk或hibernate都提供了对object对象的校验,只需加上相应的注解即可。

1.项目建立

java使用validator进行校验

 pom.xml

[html] view plain copy
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">  
  <modelVersion>4.0.0</modelVersion>  
  <groupId>com.fei</groupId>  
  <artifactId>validation-test</artifactId>  
  <version>0.0.1-SNAPSHOT</version>  
    
  <dependencies>  
    
    <dependency>  
        <groupId>javax.el</groupId>  
        <artifactId>javax.el-api</artifactId>  
        <version>2.2.4</version>  
    </dependency>  
      
  <dependency>  
        <groupId>org.hibernate</groupId>  
        <artifactId>hibernate-validator</artifactId>  
        <version>5.1.3.Final</version>  
    </dependency>  
    
  </dependencies>  
    
</project>2.基本校验练习
StudentInfo.java


[java] view plain copy
package com.fei.info;  
  
import javax.validation.constraints.Pattern;  
  
import org.hibernate.validator.constraints.NotBlank;  
  
public class StudentInfo {  
  
    @NotBlank(message="用户名不能为空")  
    private String userName;  
      
    @NotBlank(message="年龄不能为空")  
    @Pattern(regexp="^[0-9]{1,2}$",message="年龄是整数")  
    private String age;  
      
    /** 
     * 如果是空,则不校验,如果不为空,则校验 
     */  
    @Pattern(regexp="^[0-9]{4}-[0-9]{2}-[0-9]{2}$",message="出生日期格式不正确")  
    private String birthday;  
      
    @NotBlank(message="学校不能为空")  
    private String school;  
  
    public String getUserName() {  
        return userName;  
    }  
  
    public void setUserName(String userName) {  
        this.userName = userName;  
    }  
  
    public String getAge() {  
        return age;  
    }  
  
    public void setAge(String age) {  
        this.age = age;  
    }  
  
    public String getBirthday() {  
        return birthday;  
    }  
  
    public void setBirthday(String birthday) {  
        this.birthday = birthday;  
    }  
  
    public String getSchool() {  
        return school;  
    }  
  
    public void setSchool(String school) {  
        this.school = school;  
    }  
}  
ValidatorUtil.java

[java] view plain copy
package com.fei.util;  
  
import java.util.HashMap;  
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;  
  
public class ValidatorUtil {  
    private static Validator validator = Validation.buildDefaultValidatorFactory()  
            .getValidator();  
      
    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;  
    }  
  
     
}  
ValidatorTest.java

[java] view plain copy
package com.fei;  
  
import java.util.Map;  
  
import com.fei.info.StudentInfo;  
import com.fei.util.ValidatorUtil;  
  
public class ValidatorTest {  
  
    public static void main(String[] args) {  
        StudentInfo s = new StudentInfo();  
        long startTime = System.currentTimeMillis();  
        print(ValidatorUtil.validate(s));  
        System.out.println("===============耗时(毫秒)=" + (System.currentTimeMillis() - startTime));  
          
        s.setUserName("小明");  
        s.setAge("a10");  
        s.setBirthday("2016-9-1");  
        startTime = System.currentTimeMillis();  
        print(ValidatorUtil.validate(s));  
        System.out.println("===============耗时(毫秒)=" + (System.currentTimeMillis() - startTime));  
          
          
          
    }  
      
    private static void print(Map<String,StringBuffer> errorMap){  
        if(errorMap != null){  
            for(Map.Entry<String, StringBuffer> m : errorMap.entrySet()){  
                System.out.println(m.getKey() + ":" + m.getValue().toString());  
            }  
        }  
    }  
}  

来看看运行结果:

[plain] view plain copy
十二月 12, 2016 4:02:00 下午 org.hibernate.validator.internal.util.Version <clinit>  
INFO: HV000001: Hibernate Validator 5.1.3.Final  
school:学校不能为空  
age:年龄不能为空  
userName:用户名不能为空  
===============耗时(毫秒)=280  
birthday:出生日期格式不正确  
school:学校不能为空  
age:年龄是整数  
===============耗时(毫秒)=3  

 

java使用validator进行校验

上一篇:C#执行OracleHelper


下一篇:函数式编程让你忘记设计模式