【问题标题】:Dropwizard custom validation annotation not workingDropwizard自定义验证注释不起作用
【发布时间】:2016-07-01 21:08:26
【问题描述】:

我正在尝试使用这样的自定义验证注释一次应用多个常见注释:

@Retention(RetentionPolicy.RUNTIME)
@Length(max=25, min=1, message="invalid length")
@NotNull
@Pattern(regexp = "[a-zA-Z0-9]{1, 25})")
public @interface MyAnnotation {
}

并在我的模型类中使用它,如下所示:

@MyAnnotation
public String firstName;

这些验证都不起作用,但在模型类本身中使用时它们会按预期工作。我还尝试在应用程序运行方法中注册 MyAnnotation,但也没有用。

environment.jersey().register(MyAnnotation.class);

为了使用自定义验证,我还需要做什么?

【问题讨论】:

标签: java validation jersey dropwizard


【解决方案1】:

要么直接注释字符串:

@Pattern(regexp = "[a-zA-Z0-9]{1, 25})")
@NotNull
@Length(max=25, min=1, message="invalid length")
public String firstName; 

或者创建一个验证器,比如:

class MyAnnotatationValidator implements ConstraintValidator<MyAnnotation, String>{
  @Override
  public void initialize(MyAnnotation a){}
  @Override
  public boolean isValid(String s, ConstraintValidationContext c) {
    return s != null && (s.length() > 0 && s.length() < 26) && s.matches("[a-zA-Z0-9]{1, 25})";  
  }
}

还有

@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy=MyAnnotatationValidator.class)
public @interface MyAnnotation {
  String message() default = "{MyAnnotation}";
  Class<?>[] groups() default {};
  Class<? extends Payload> payload() deafult {};
}

【讨论】:

    【解决方案2】:

    根据JSR-303

    约束定义可能具有在将约束应用于 JavaBean 时指定的属性。属性被映射为注释元素。注释元素名称消息、组和有效负载被认为是保留名称;不允许以 valid 开头的注释元素;约束可以为其属性使用任何其他元素名称。

    因此,您必须将消息、组和有效负载属性添加到您的 @MyAnnotation。
    通过注释组合约束来完成组合,例如:

    @Length(max=25, min=1, message="invalid length")
    @NotNull
    @Pattern(regexp = "[a-zA-Z0-9]{1, 25})")
    @Documented
    @Target({ANNOTATION_TYPE, METHOD, FIELD, CONSTRUCTOR, PARAMETER})
    @Retention(RUNTIME)
    public @interface MyAnnotation {
        String message() default "My annotation message";
        Class<?>[] groups() default {};
        Class<? extends Payload>[] payload() default {};
    }
    

    【讨论】:

    • 这不起作用,由于某种原因没有应用验证。
    • 你能分享更多关于你的代码的细节吗?您是在尝试验证 POST 正文,例如:@POST public void validPost(@Valid MyBean mybean) {} 还是在 JPA 层中?
    猜你喜欢
    • 2017-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多