【问题标题】:DropWizard @ValidationMethod Change property nameDropWizard @ValidationMethod 更改属性名称
【发布时间】:2015-06-17 10:35:32
【问题描述】:

我在 Dropwizard 中有一个表示,其中包含带有注释 @ValidationMethod 的方法。

Dropwizard 示例:

@ValidationMethod(message="may not be Coda")
public boolean isNotCoda() {
return !("Coda".equals(name));
}

请注意,方法必须以“is”开头。这是 Hibernate Validator 的限制。

我的例子:

@NotBlank(message = REQUIRED)
private String password;


@JsonIgnore
@ValidationMethod(message = "the password fields must match")
public boolean isPasswordEqualRepeatedPassword() {
    
}

@JsonIgnore
@ValidationMethod(message = "the password must not contain or be equal to the username")
public boolean isNotEqualOrContainUsername(){

}

目前的回应:

"field" : "PasswordEqualRepeatedPassword", "message" = "密码字段必须匹配"

"field" : "NotEqualOrContainUsername", "message" = "密码不能包含或等于用户名"

我希望该字段与类属性一样等于密码。问题是我不能命名 isPassword() 的方法得到以下响应:

“字段”:“密码”, "message" = "密码字段必须匹配"

“字段”:“密码”, "message" = "密码不能包含或等于用户名"

有没有办法做到这一点?

【问题讨论】:

    标签: java jackson dropwizard hibernate-validator


    【解决方案1】:

    不幸的是,通过重新实现 dropwizard 已实现的许多功能,这是可行的。我们需要在错误时返回自定义对象,并且还有其他缺点,所以进入了一些反射兔子洞。不过我们很久以前就实现了,所以现在可能会更容易,所以我将分享相关的部分来完成它。

    对于这个特定问题,我们通过向验证消息添加自定义字符串格式来解决问题。

      @ValidationMethod(message = "[password]the password fields must match")
    

    然后当我们解析消息时,我们抓取“密码”字段。

    首先,我们通过实现异常映射器自己处理验证错误。

    public class UnprocessableEntityExceptionMapper implements ExceptionMapper<ConstraintViolationException> {
    
      @Override
      public Response toResponse(ConstraintViolationException exception) {
        return Response
            .status(422)
            .entity(doMagic(exception))
            .type(MediaType.APPLICATION_JSON_TYPE)
            .build();
      }
    }
    

    doMagic 是潜在的兔子洞,但我建议尝试并在那里调试,然后返回一个对象,该对象将代表您在 JSON 中的错误。相关位:

    • exception.getConstraintViolations() 将返回要处理的违规列表。
    • constraintViolation.getConstraintDescriptor().getAnnotation() instanceof ValidationMethod 是您知道它是 dropwizard ValidationMethod 的方式。
    • 在本例中,constraintViolation.getMessage() 将返回 "[password]the password fields must match"

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-18
      • 2023-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-24
      • 2017-07-28
      • 1970-01-01
      相关资源
      最近更新 更多