参数校验工具之Validator:注解方式实现

hibernate validator :官方文档:http://hibernate.org/validator/

https://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/#preface

一、总结项目中参数校验技术实现

在需要注解的方法实现增加注解@ValidationInputParameter

并在方法的入参实体上增加注解eg:


@NotBlank(message = BizResponseCodeConstant.QRCODE_IS_ERROR)
private String qrCode;

 

实现的原理:

1.入参校验注解接口


@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ValidationInputParameter {
}

2.入参校验拦截器


public class InnerFacadeInvokeValidationInterceptor implements MethodInterceptor {
    private static Logger LOGGER = LoggerFactory.getLogger(InnerFacadeInvokeValidationInterceptor.class);

    public InnerFacadeInvokeValidationInterceptor() {
    }

    public Object invoke(MethodInvocation methodInvocation) throws Throwable {
        long startTime = System.currentTimeMillis();
        Method method = methodInvocation.getMethod();
        String methodName = method.getDeclaringClass().getSimpleName() + "." + method.getName();
        Object[] arguments = methodInvocation.getArguments();
        Object result = null;
        if (null != arguments && arguments.length > 0) {
            Object[] var8 = arguments;
            int var9 = arguments.length;

            for(int var10 = 0; var10 < var9; ++var10) {
                Object object = var8[var10];
                ValidationUtils.validateEntity(object);
            }

            String methodInputJsonString = JSON.toJSONString(arguments);
            ValidationUtils.isContainIllegalCharacter(methodInputJsonString);
        }

        long time = System.currentTimeMillis() - startTime;
        result = methodInvocation.proceed();
        LOGGER.info("[返回结果] - {} - {},[执行时间] - 耗时{}毫秒", new Object[]{methodName, ToStringBuilder.reflectionToString(result), time});
        return result;
    }
}

实现自定义的参数校验规则 增加@Constraint(validatedBy={}) 指明使用那个校验器(类) 去校验使用了此标注的元素.


@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(
    validatedBy = {JsonNotEmptyValidator.class}
)
public @interface JsonNotEmpty {
    String field() default "";

    String message() default "";

    String errorCode() default "";

    Class[] groups() default {};

    Class[] payload() default {};
}

校验器的实现


public class JsonNotEmptyValidator implements ConstraintValidator {
    private String fieldList = "";

    public JsonNotEmptyValidator() {
    }

    public void initialize(JsonNotEmpty jsonNotEmptys) {
        this.fieldList = jsonNotEmptys.field();
    }

    public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
        try {
            if (StringUtils.isEmpty(value)) {
                return false;
            } else {
                String[] fieldArray = this.fieldList.split(",");
                if (null != fieldArray && fieldArray.length > 0) {
                    for(int i = 0; i < fieldArray.length; ++i) {
                        JSONObject jsonObject = JSON.parseObject(value);
                        String jsonField = fieldArray[i];
                        if (!jsonObject.containsKey(jsonField)) {
                            ValidateImplementUtil.setErrorField(new String[]{jsonField});
                            return false;
                        }

                        String fieldValue = jsonObject.getString(jsonField);
                        if (!ValidateImplementUtil.validatorCommon(ValidatorEnum.NOT_EMPTY, fieldValue, (Class)null)) {
                            ValidateImplementUtil.setErrorField(new String[]{jsonField});
                            return false;
                        }
                    }
                }

                return true;
            }
        } catch (Exception var8) {
            return false;
        }
    }
}

 

你可能感兴趣的:(参数校验工具之Validator:注解方式实现)