Java参数校验

基本步骤

  1. 引入pom依赖
  2. 书写需要校验的实体
  3. 书写实体校验工具类
  4. 编写测试代码

引入pom依赖

        
        
        
            javax.validation
            validation-api
            2.0.1.Final
        
        
            org.hibernate
            hibernate-validator
            6.0.14.Final
        
        
            org.glassfish
            javax.el
            3.0.1-b11
        
        

书写需要校验的实体

package com.ahut.common.utils;

import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;

/**
 * desc : 新增用户请求
 * create_user : cheng
 * create_date : 2019/1/23 11:34
 */
public class AddUserRequest {

    /**
     * 用户名
     */
    @NotNull(message = "用户名不能为空")
    private String userName;
    /**
     * 年龄
     */
    @Min(value = 0, message = "用户年龄最小为0")
    private int age;


    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

书写实体校验工具类

package com.ahut.common.utils;

import com.ahut.common.entity.BeanValidateResult;
import org.apache.commons.collections.CollectionUtils;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * desc : 实体校验工具类
 * create_user : cheng
 * create_date : 2019/1/23 13:54
 */
public final class BeanValidateUtil {

    /**
     * 私有化构造方法
     */
    private BeanValidateUtil() {
    }

    /**
     * desc : 校验
     * create_user : cheng
     * create_date : 2019/1/23 13:56
     */
    public static  List validate(T bean) {
        // 校验null
        if (Objects.isNull(bean)) {
            return getNullValidateResultList();
        }

        // 获取验证器工厂
        ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
        // 获取验证器
        Validator validator = validatorFactory.getValidator();
        // 执行验证
        Set> validateSet = validator.validate(bean);
        return getValidateResultList(validateSet);
    }

    /**
     * desc : 获取校验实体list
     * create_user : cheng
     * create_date : 2019/1/23 14:12
     */
    private static  List getValidateResultList(Set> validateSet) {
        List validateResultList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(validateSet)) {
            validateResultList = validateSet.stream().map(BeanValidateUtil::convertToBeanValidateResult).collect(Collectors.toList());
        }
        return validateResultList;
    }

    /**
     * desc : 转换类型
     * create_user : cheng
     * create_date : 2019/1/23 14:48
     */
    private static  BeanValidateResult convertToBeanValidateResult(ConstraintViolation validate) {
        BeanValidateResult validateResult = new BeanValidateResult();
        validateResult.setFieldName(validate.getPropertyPath().toString());
        validateResult.setMessage(validate.getMessage());
        return validateResult;
    }
    /**
     * desc : 获取bean为null时的校验结果
     * create_user : cheng
     * create_date : 2019/1/24 10:39
     */
    private static List getNullValidateResultList() {
        List validateResultList = new ArrayList<>();
        BeanValidateResult validateResult = new BeanValidateResult();
        validateResult.setFieldName("validateBean");
        validateResult.setMessage("bean is null");
        validateResultList.add(validateResult);
        return validateResultList;
    }

}
package com.ahut.common.entity;

/**
 * desc : 参数校验结果封装实体
 * create_user : cheng
 * create_date : 2019/1/23 14:45
 */
public class BeanValidateResult {

    private String fieldName;

    private String message;

    public String getFieldName() {
        return fieldName;
    }

    public void setFieldName(String fieldName) {
        this.fieldName = fieldName;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

编写测试代码

package com.ahut.common.utils;

import com.ahut.common.entity.BeanValidateResult;
import org.junit.Test;

import java.util.List;

/**
 * desc : 测试参数校验
 * create_user : cheng
 * create_date : 2019/1/23 14:21
 */
public class BeanValidateUtilTest {

    /**
     * desc :
     * create_user : cheng
     * create_date : 2019/1/23 14:21
     */
    @Test
    public void testValidate() {
        AddUserRequest request = new AddUserRequest();
        request.setAge(-1);

        List validateResultList = BeanValidateUtil.validate(request);
        for (BeanValidateResult validateResult : validateResultList) {
            System.out.println(validateResult.getFieldName() + " : " + validateResult.getMessage());
        }
    }

}

输出结果

userName : 用户名不能为空
age : 用户年龄最小为0

自定义注解

定义注解

package com.ahut.common.annotation;

import com.ahut.common.annotation.validate.ListIsNotEmptyValidator;

import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * desc : 校验list不为空的注解
 * create_user : cheng
 * create_date : 2019/1/24 16:33
 */
@Target({ElementType.FIELD, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = ListIsNotEmptyValidator.class)
public @interface ListIsNotEmpty {

    String message() default "{com.ahut.common.annotation.ListIsNotEmpty.message}";

    Class[] groups() default {};

    Class[] payload() default {};
}

定义注解校验器

package com.ahut.common.annotation.validate;

import com.ahut.common.annotation.ListIsNotEmpty;
import org.apache.commons.collections.CollectionUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.List;

/**
 * desc : 验证ListIsNotEmpty注解
 * create_user : cheng
 * create_date : 2019/1/24 16:38
 */
public class ListIsNotEmptyValidator implements ConstraintValidator {

    /**
     * desc :
     * create_user : cheng
     * create_date : 2019/1/24 16:49
     */
    @Override
    public boolean isValid(List list, ConstraintValidatorContext constraintValidatorContext) {
        return CollectionUtils.isNotEmpty(list);
    }

    /**
     * desc : 初始化
     * create_user : cheng
     * create_date : 2019/1/24 16:49
     */
    @Override
    public void initialize(ListIsNotEmpty constraintAnnotation) {
    }

}

你可能感兴趣的:(JaveSE,JavaEE)