java使用validator进行校验

html页面表单提交的对象数据或者接口对接,都需要对接收到的数据进行校验(非空、长度、格式等等),jdk或hibernate都提供了对object对象的校验,只需加上相应的注解即可。
引入pom


	org.hibernate.validator
	hibernate-validator
	6.0.13.Final

			

待校验的实体类

public class StudentInfo {
 	@NotBlank(message="用户名不能为空",groups = { ValidGroup.class})
	private String userName;
	@NotBlank(message="年龄不能为空",groups = { ValidGroup.class})
	@Pattern(regexp="^[0-9]{1,2}$",message="年龄是整数",groups = { ValidGroup.class})
	private String age;
    @Pattern(regexp="^[0-9]{4}-[0-9]{2}-[0-9]{2}$",message="出生日期格式不正确",groups = { ValidGroup.class})
	private String birthday;
	@NotBlank(message="学校不能为空",groups = { ValidGroup.class})
	private String school;
}

BeanValidateUtil

public class BeanValidateUtil {
    private static ValidatorFactory factory = Validation.buildDefaultValidatorFactory();

    public static  Map validate(T t) {   
    	Map errorMap = null;
        Validator validator = factory.getValidator();
        Set> constraintViolations = validator.validate(t);
        for (ConstraintViolation constraintViolation : constraintViolations) {
        	   //这里循环获取错误信息,可以自定义格式
            	property = constraintViolation .getPropertyPath().toString();
            	if(errorMap.get(property) != null){
            		errorMap.get(property).append("," + constraintViolation .getMessage());
            	}else{
            		StringBuffer sb = new StringBuffer();
            		sb.append(constraintViolation .getMessage());
            		errorMap.put(property, sb);
            	}
        }
        return errorMap;
    }

    public static  Map validateGroup(T t, Class classType) {
    	Map errorMap = null;
        Validator validator = factory.getValidator();
        Set> constraintViolations = validator.validate(t, classType);
        for (ConstraintViolation constraintViolation : constraintViolations) {
               //这里循环获取错误信息,可以自定义格式
            	property = constraintViolation .getPropertyPath().toString();
            	if(errorMap.get(property) != null){
            		errorMap.get(property).append("," + constraintViolation .getMessage());
            	}else{
            		StringBuffer sb = new StringBuffer();
            		sb.append(constraintViolation .getMessage());
            		errorMap.put(property, sb);
            	}
        }
        return erroMap;
    }

你可能感兴趣的:(#,hibernate)