一、引入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编写
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 public class BeanValidator { 2 3 private static ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory(); 4 5 /** 6 * 校验对象 7 * @param t 对象的泛型 8 * @param groups 9 * @param <T> 10 * @return 11 */ 12 public static <T>Map<String,String> 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<String,String> 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 * <p>校验参数之后不会处理只会将错误信息存储到map中 50 * @param first 51 * @param objects 52 */ 53 public static Map<String,String> 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 * <p>当校验参数不合法时抛出异常让程序不能继续执行 64 * @param param 65 * @throws ParamException 66 */ 67 public static void check(Object param)throws ParamException{ 68 Map<String, String> map = validateObject(param); 69 if(MapUtils.isNotEmpty(map)){ 70 throw new ParamException(map.toString()); 71 } 72 } 73 }
四、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"; } }
运行就会输出这样的日志信息: