springboot自定义注解校验参数

由于已有校验注解不满足业务,所以有时候会需要自己定义校验注解
例如此业务中,驾驶本类型,由于是二期项目,并且驾驶本类型不是字典,是写死的,为常量类,所以需要校验前端传入的汉字是否符合规定

1、首先定义一个自定义注解,

import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.*;


/**
 * 自定义驾驶证校验
 * @author zn
 */
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(validatedBy = {IsDrivingLicenseTypeValidator.class})
public @interface IsDrivingLicenseType {

    //默认参数为必填
    boolean required() default true;

    String message() default "驾驶本类型错误 请从指定类型选择!";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};


}

2、定义一个校验类

import com.yidu.excel.utils.StringUtils;
import com.yidu.oa.core.constant.DrivingLicenseTypeConstant;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * @author : tp
 * @since :Created in 2022/5/21 11:32
 */
public class IsDrivingLicenseTypeValidator  implements ConstraintValidator<IsDrivingLicenseType,String> {
    @Override
    public void initialize(IsDrivingLicenseType constraintAnnotation) {

    }

    @Override
    public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
        if (StringUtils.isBlank(s)){
            return true;
        }
        return DrivingLicenseTypeConstant.check(s);
    }
}

3、调用常量类中的方法进行判断

/**
 * @desc 驾驶本常量类
 * @author : tp
 * @since :Created in 2022/5/21 11:08
 */
public class DrivingLicenseTypeConstant {



    public static final String A1 = "A1本";

    public static final String A2 = "A2本";

    public static final String A3 = "A3本";

    public static final String B1 = "B1本";

    public static final String B2 = "B2本";

    public static final String C1 = "C1本";

    public static final String C2 = "C2本";

    public static final String C3 = "C3本";

    public static final String C4 = "C4本";

    public static final String D = "D本";

    public static final String E = "E本";

    public static final String F = "F本";

    public static final String M = "M本";

    public static final String N = "N本";

    public static final String P = "P本";

    public static final String[] ALL_TYPE = {A1,A2,A3,B1,B2,C1,C2,C3,C4,D,E,F,M,N,P};

    /**
     * 判断 前段传入的驾驶本类型 是否正确
     * 本分数据库未保存驾驶本ID,保存的汉字
     * @param string
     * @return
     */
    public static boolean check(String string){
        string = string.replaceAll(",",",");
        List<String> list  = Arrays.asList(string.split(","));
        for (String s : list) {
            boolean contains = Arrays.asList(ALL_TYPE).contains(s);
            if (!contains) {
                return contains;
            }
        }
        return true;
    }
}

4、实体类上增加注解

     @Excel(name = "驾照类型")
     @NotBlank(message = "驾照类型不能为空")
     @IsDrivingLicenseType()
     private String drivingLicenseType;

5、controller增加开启校验的注解即可

   @PostMapping("/post")
    public DataResult post(@Validated @RequestBody User person) {
        return DataResult.success();
    }

6、如果不想或者无法在controller调用,例如导入导出,或者方法内部某个方法需要判断,可以手动调用方法执行

List<String> list1 = ValidatorUtil.validateAll(carDriverdDto);

import org.apache.commons.lang3.StringUtils;
import org.hibernate.validator.HibernateValidator;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author : tp
 * @since :Created in 2022/5/21 10:35
 */
public class ValidatorUtil {


    private static Validator validatorFast = Validation.byProvider(HibernateValidator.class).configure().failFast(true).buildValidatorFactory().getValidator();
    private static Validator validatorAll = Validation.byProvider(HibernateValidator.class).configure().failFast(false).buildValidatorFactory().getValidator();

    /**
     * 校验遇到第一个不合法的字段直接返回不合法字段,后续字段不再校验
     * @Time 2020年6月22日 上午11:36:13
     * @param 
     * @param domain
     * @return
     * @throws Exception
     */
    public static <T> Set<ConstraintViolation<T>> validateFast(T domain) throws Exception {
        Set<ConstraintViolation<T>> validateResult = validatorFast.validate(domain);
        if(validateResult.size()>0) {
            System.out.println(validateResult.iterator().next().getPropertyPath() +":"+ validateResult.iterator().next().getMessage());
        }
        return validateResult;
    }

    /**
     * 校验所有字段并返回不合法字段
     * @Time 2020年6月22日 上午11:36:55
     * @param 
     * @param domain
     * @return
     * @throws Exception
     */
    public static <T> List<String> validateAll(T domain) throws Exception {
        Set<ConstraintViolation<T>> validateResult = validatorAll.validate(domain);
        List<String> list = new ArrayList<>();
        if(validateResult.size()>0) {
            Iterator<ConstraintViolation<T>> it = validateResult.iterator();
            while(it.hasNext()) {
                ConstraintViolation<T> cv = it.next();
//                list.add(cv.getPropertyPath()+":"+cv.getMessage());
                list.add(cv.getMessage());
                System.out.println(cv.getPropertyPath()+":"+cv.getMessage());
            }
        }
        return list;
    }


}

你可能感兴趣的:(spring,boot,java,spring)