后台开发需要对对象的传进来的参数进行校验,有专门的校验工具,validation bean 是基于JSR-303标准开发出来的,使用注解方式实现,及其方便,但是这只是一个接口,没有具体实现.Hibernate Validator是一个hibernate独立的包,可以直接引用,他实现了validation bean同时有做了扩展,比较强大。
要使用在pom.xml里添加依赖
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.4.1.Final</version>
</dependency>
对要验证的类添加的注解
一个用于VO继承的父对象,实现了一个Validate方法,可以抛出自定义异常,然后把违背约束的属性给输出出来
import java.io.Serializable;
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 BaseVO implements Serializable, Cloneable {
private static final long serialVersionUID = -3282093394377931421L;
//得到一个验证器实例
private static Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
//验证方法,抛出自定义异常
public void validate() throws XXXException{
//用Map保存错误
Map<String, StringBuffer> errorMap = null;
//把对象放到验证器的验证方法中,用Set存储违背约束的对象
Set<ConstraintViolation<BaseVO>> set = validator.validate(this, Default.class);
//当有违背约束的对象时
if (set != null && set.size() > 0) {
//初始化map
errorMap = new HashMap<String, StringBuffer>();
//保存错误属性
String property = null;
for (ConstraintViolation<BaseVO> 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);
}
}
if (errorMap != null) {
StringBuffer sb = new StringBuffer();
for (Map.Entry<String, StringBuffer> m : errorMap.entrySet()) {
sb.append(m.getValue().toString()).append("\r\n");
}
//输出
throw new XXXException(sb.toString());
}
}
}
}
或者参照这个博客可以将其封装成工具类
package com.alibaba.banff.web.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;
/**
* 校验工具类
*
* @author lizhilong
*/
public class ValidationUtils {
private static Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
public static <T> ValidationResult validateEntity(T obj) {
ValidationResult result = new ValidationResult();
Set<ConstraintViolation<T>> set = validator.validate(obj, Default.class);
// if( CollectionUtils.isNotEmpty(set) ){
if (set != null && set.size() != 0) {
result.setHasErrors(true);
Map<String, String> errorMsg = new HashMap<String, String>();
for (ConstraintViolation<T> cv : set) {
errorMsg.put(cv.getPropertyPath().toString(), cv.getMessage());
}
result.setErrorMsg(errorMsg);
}
return result;
}
public static <T> ValidationResult validateProperty(T obj, String propertyName) {
ValidationResult result = new ValidationResult();
Set<ConstraintViolation<T>> set = validator.validateProperty(obj, propertyName, Default.class);
if (set != null && set.size() != 0) {
result.setHasErrors(true);
Map<String, String> errorMsg = new HashMap<String, String>();
for (ConstraintViolation<T> cv : set) {
errorMsg.put(propertyName, cv.getMessage());
}
result.setErrorMsg(errorMsg);
}
return result;
}
}
校验工具类返回的数据ValidationResult(省略getset):
package com.aliyun.prophet.facade.partner.flaw;
import java.util.Map;
/**
* 校验结果
*
* @author lizhilong
*/
public class ValidationResult {
// 校验结果是否有错
private boolean hasErrors;
// 校验错误信息
private Map<String, String> errorMsg;
}