【问题标题】:Java Spring Validation and custom patternsJava Spring 验证和自定义模式
【发布时间】:2023-04-01 23:01:01
【问题描述】:

我有一个获取客户信息的 DTO 类。许多字段都带有验证限制注释。 @NotNull @Length @Min @Max @Pattern... 等等。我们需要从属性文件加载正则表达式以进行验证,因此我们需要创建 @CustomPattern 以及 CustomerValidationAdvice。

@Before("@annotation(customPattern)")
public void validateWithPropertyFileValue(JoinPoint joinPoint, CustomPattern customPattern) throws Throwable {
    if(applicationProps==null) {
        applicationProps = (Properties) ApplicationContextProvider.getApplicationContext().getBean(
                "applicationProps");
    }
    Object[] paramValues = joinPoint.getArgs();
    String valueToValidate="";
    if (!ArrayUtils.isEmpty(paramValues)) {
        valueToValidate = paramValues[0] != null ? (String) paramValues[0] : valueToValidate;
    }
    if (!serverValidationUsingRegexPattern(valueToValidate, applicationProps.getProperty(customPattern.regexp()))) {
        throw new ValidationException("Validation Failed");
    }

}

问题在于,当从传入请求设置 DTO 上的值时,即使该方法未使用 @Valid 注释,也会执行此操作。除非将对象传递给验证器或 @valid 在方法上,否则不会执行其他验证参数。我可以在 joinPoint 中查看哪些内容来确定它是从哪里调用的并跳过验证?

【问题讨论】:

    标签: java spring validation


    【解决方案1】:

    似乎最好采用正常验证的工作方式。因此,不要尝试使用方面来修改遗留代码。我创建了 2 个文件
    注释:

    @Documented
    @Retention(RUNTIME)
    @Target({METHOD,FIELD})
    @Constraint(validatedBy=PropertyPaternValidator.class)
    public @interface PropertyPatern {
        String property();
        String message() default "{validator.propertypatern}";
        Class<?>[] groups() default {};
        Class<? extends Payload>[] payload() default {};
    
    }  
    

    和处理器:

    public class PropertyPaternValidator implements ConstraintValidator<PropertyPatern, CharSequence> {
    
        private Map<String, Pattern> patterns = new HashMap<>();
        private Pattern pattern;
    
        @Override
        public void initialize(PropertyPatern propPattern) {
            String property = propPattern.property();
    
            pattern = patterns.computeIfAbsent(property, prop -> {
                Properties applicationProps = (Properties) ApplicationContextProvider.getApplicationContext()
                    .getBean("applicationProps");
                String p = applicationProps.getProperty(prop);
                return Pattern.compile(p);
            });
        }    
        @Override
        public boolean isValid(CharSequence inputToValidate, ConstraintValidatorContext ctx) {
            CharSequence input = inputToValidate != null ? inputToValidate : "";
            Matcher m = pattern.matcher(input);
            return m.matches();
        }
    }
    

    这将像@Pattern 一样工作,但允许从应用程序属性加载正则表达式。用法注释字段,如 @PropertyPatern(property = "pattern.zip") 并确保应用程序属性中有一个带有该键的正则表达式。

    【讨论】:

      猜你喜欢
      • 2014-02-26
      • 1970-01-01
      • 1970-01-01
      • 2018-10-14
      • 2014-11-04
      • 1970-01-01
      • 2016-09-05
      • 2012-08-26
      • 2011-06-15
      相关资源
      最近更新 更多