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

一、引入pom依赖


<dependency>
    <groupId>javax.validationgroupId>
    <artifactId>validation-apiartifactId>
    <version>1.1.0.Finalversion>
dependency>
<dependency>
    <groupId>org.hibernategroupId>
    <artifactId>hibernate-validatorartifactId>
    <version>5.2.4.Finalversion>
dependency>

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

@Data
public class TestVo {

    @NotNull
    private Integer id ;

    @NotBlank
    private String name;
}

三、工具类BeanValidator编写

 1 public class BeanValidator {
 2 
 3     private static ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
 4 
 5     /**
 6      * 校验对象
 7      * @param t 对象的泛型
 8      * @param groups
 9      * @param 
10      * @return
11      */
12     public static Map validate(T t,Class... groups){
13         Validator validator = validatorFactory.getValidator();
14         Set validateResult = validator.validate(t, groups);
15         if(validateResult.isEmpty()){
16             return Collections.emptyMap();
17         }else {
18             LinkedHashMap errors = Maps.newLinkedHashMap();
19             Iterator iterator = validateResult.iterator();
20             while (iterator.hasNext()){
21                 ConstraintViolation violation = (ConstraintViolation) iterator.next();
22                 errors.put(violation.getPropertyPath().toString(),violation.getMessage());
23             }
24             return errors;
25         }
26     }
27 
28     /**
29      * 校验集合
30      * @param collection 集合
31      * @return
32      */
33     public static Map validateList(Collection collection){
34         Preconditions.checkNotNull(collection);
35         Iterator iterator = collection.iterator();
36         Map errors;
37         do{
38             if (!iterator.hasNext()) {
39                 return Collections.emptyMap();
40             }
41             Object object = iterator.next();
42             errors = validate(object,new Class[0]);
43         }while (errors.isEmpty()); // 如果errors为空则循环校验,一旦不为空   跳出循环
44         return errors;
45     }
46 
47     /**
48      * 通用方法,至少传入一个Object参数
49      * 

校验参数之后不会处理只会将错误信息存储到map中 50 * @param first 51 * @param objects 52 */ 53 public static Map validateObject(Object first,Object... objects){ 54 if(objects == null || objects.length == 0){ 55 return validate(first,new Class[0]); 56 }else { 57 return validateList(Lists.asList(first,objects)); 58 } 59 } 60 61 /** 62 * 校验参数是否合法 63 *

当校验参数不合法时抛出异常让程序不能继续执行 64 * @param param 65 * @throws ParamException 66 */ 67 public static void check(Object param)throws ParamException{ 68 Map map = validateObject(param); 69 if(MapUtils.isNotEmpty(map)){ 70 throw new ParamException(map.toString()); 71 } 72 } 73 }

View Code

四、Controller类中调用并测试

 

@Controller
@Slf4j
@RequestMapping("/test")
public class TestController {

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

}

 

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

 

你可能感兴趣的:(JSR303完成validate校验并编写BeanValidator工具类)