javax.validation 效验工具(validation-api组件)使用教程

在后端开发时,不可避免的需要处理一些校验, 如果是写if-else这种代码去校验, 那会有一大段这样的代码。不过还好有个校验插件:javax.validation.validation-api,不过一般会引用hibernate的校验组件:org.hibernate.hibernate-validator, 它已经引用了validation-api组件。

首先pom.xml引入依赖

   
        
            javax.validation
            validation-api
            1.1.0.Final
        
        
            org.hibernate
            hibernate-validator
            5.2.4.Final
        

Spring配置注入bean

自己的Violation实体

这里使用的Lombok获取get和set,使用的@Getter注解 @Setter注解

import java.util.List;

/**
 * @Auther: Summer
 * @Date: 2019-01-05 11:35
 * @Description:  测试实体类
 * @versions:1.0
 */
@Getter
@Setter
public class TestVo {
    @NotBlank   // @NotBlank 必须是String类型的
    private  String  msg;
    @NonNull  // @NotNull:不能为null,但可以为empty,没有Size的约束
    private String id;

    private List str;
}

接口工具类util

/**
 * @Auther: Summer
 * @Date: 2019-01-05 11:00
 * @Description: 接口效验
 * @versions:1.0
 */
public class BeanValidator {
    private static ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();

    public static  Map 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;
        }
    }

    public static Map 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());

        return errors;
    }

    public static Map validateObject(Object first, Object... objects) {
        if (objects != null && objects.length > 0) {
            return validateList(Lists.asList(first, objects));
        } else {
            return validate(first, new Class[0]);
        }
    }

通过controller 验证Slf4j的log.info打印日志信息验证是否成功

package com.mmall.controller;
import com.mmall.common.JsonDate;
import com.mmall.param.TestVo;
import com.mmall.util.BeanValidator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.Map;
@Controller
@RequestMapping("/test")
@Slf4j
public class TestController {
    @RequestMapping("/validate.json")
    @ResponseBody
    public JsonDate validate(TestVo vo){
         log.info("validate");
         try {
             Map map = BeanValidator.validateObject(vo);
             if(map != null && map.entrySet().size() >0){
                 for (Map.Entry entry: map.entrySet()){
                     log.info("{}->{}",entry.getKey(),entry.getValue());
                 }
             }
         }catch (Exception e){

         }
        return JsonDate.success("test,validate");
    }
}

打印结果:

javax.validation 效验工具(validation-api组件)使用教程_第1张图片

附注解图:

javax.validation 效验工具(validation-api组件)使用教程_第2张图片

你可能感兴趣的:(Java工具/插件类)