一、引入pom依赖

<!-- validator -->
<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.2.4.Final</version>
</dependency>

二、针对需要验证的字段封装为TestVo

@Data
public class TestVo { @NotNull
private Integer id ; @NotBlank
private String name;
}

三、工具类BeanValidator编写

 public class BeanValidator {

     private static ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();

     /**
* 校验对象
* @param t 对象的泛型
* @param groups
* @param <T>
* @return
*/
public static <T>Map<String,String> validate(T t,Class... groups){
Validator validator = validatorFactory.getValidator();
Set validateResult = validator.validate(t, groups);
if(validateResult.isEmpty()){
return Collections.emptyMap();
}else {
LinkedHashMap errors = Maps.newLinkedHashMap();
Iterator iterator = validateResult.iterator();
while (iterator.hasNext()){
ConstraintViolation violation = (ConstraintViolation) iterator.next();
errors.put(violation.getPropertyPath().toString(),violation.getMessage());
}
return errors;
}
} /**
* 校验集合
* @param collection 集合
* @return
*/
public static Map<String,String> validateList(Collection<?> collection){
Preconditions.checkNotNull(collection);
Iterator iterator = collection.iterator();
Map errors;
do{
if (!iterator.hasNext()) {
return Collections.emptyMap();
}
Object object = iterator.next();
errors = validate(object,new Class[0]);
}while (errors.isEmpty()); // 如果errors为空则循环校验,一旦不为空 跳出循环
return errors;
} /**
* 通用方法,至少传入一个Object参数
* <p>校验参数之后不会处理只会将错误信息存储到map中
* @param first
* @param objects
*/
public static Map<String,String> validateObject(Object first,Object... objects){
if(objects == null || objects.length == 0){
return validate(first,new Class[0]);
}else {
return validateList(Lists.asList(first,objects));
}
} /**
* 校验参数是否合法
* <p>当校验参数不合法时抛出异常让程序不能继续执行
* @param param
* @throws ParamException
*/
public static void check(Object param)throws ParamException{
Map<String, String> map = validateObject(param);
if(MapUtils.isNotEmpty(map)){
throw new ParamException(map.toString());
}
}
}

四、Controller类中调用并测试

@Controller
@Slf4j
@RequestMapping("/test")
public class TestController { @RequestMapping("/testVo.json")
@ResponseBody
public String testVo(TestVo testVo)throws ParamException{
log.info("testVo");
Map<String, String> map = BeanValidator.validateObject(testVo);
if(MapUtils.isNotEmpty(map)){
for(Map.Entry<String,String> entry :map.entrySet()){
log.error("error==={}-->{}",entry.getKey(),entry.getValue());
}
}
//BeanValidator.check(testVo);
return "hello world";
} }

运行就会输出这样的日志信息:

JSR303完成validate校验并编写BeanValidator工具类-LMLPHP

05-27 18:51