参数校验工具之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<? extends Payload>[] payload() default {};
}

校验器的实现


public class JsonNotEmptyValidator implements ConstraintValidator<JsonNotEmpty, String> {
    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;
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值