覆盖 DropWizard ConstraintViolation 消息

Override DropWizard ConstraintViolation message

所以我想更改用于通过 DropWizard 资源验证模型的验证消息。

我正在使用 java bean 验证注释。例如,这是我要验证的字段之一:

@NotEmpty(message = "Password must not be empty.")

我可以使用验证器测试它是否按预期工作。

然而,当我使用 DropWizard 对资源进行验证时,它会向该消息添加一些额外的内容。我看到的是这个 - password Password must not be empty. (was null) 并且我在这里找到了执行此操作的代码 - https://github.com/dropwizard/dropwizard/blob/master/dropwizard-validation/src/main/java/io/dropwizard/validation/ConstraintViolations.java

具体这个方法-

public static <T> String format(ConstraintViolation<T> v) {
    if (v.getConstraintDescriptor().getAnnotation() instanceof ValidationMethod) {
        final ImmutableList<Path.Node> nodes = ImmutableList.copyOf(v.getPropertyPath());
        final ImmutableList<Path.Node> usefulNodes = nodes.subList(0, nodes.size() - 1);
        final String msg = v.getMessage().startsWith(".") ? "%s%s" : "%s %s";
        return String.format(msg,
                             Joiner.on('.').join(usefulNodes),
                             v.getMessage()).trim();
    } else {
        return String.format("%s %s (was %s)",
                             v.getPropertyPath(),
                             v.getMessage(),
                             v.getInvalidValue());
    }
}

有什么方法可以覆盖此行为吗?我只想显示我在注释中设置的消息...

ConstraintViolationExceptionMapper is the one which uses that method. In order to override it, you need to deregister it and register your own ExceptionMapper.

删除异常映射器

Dropwizard 0.8

将以下内容添加到您的 yaml 文件中。请注意,它将删除 dropwizard 添加的所有默认异常映射器。

server:
    registerDefaultExceptionMappers: false

Dropwizard 0.7.x

environment.jersey().getResourceConfig().getSingletons().removeIf(singleton -> singleton instanceof ConstraintViolationExceptionMapper);

创建并添加您自己的异常映射器

public class ConstraintViolationExceptionMapper implements ExceptionMapper<ConstraintViolationException> {

    @Override
    public Response toResponse(ConstraintViolationException exception) {
        // get the violation errors and return the response you want.
    }
}

并在您的应用程序中添加您的异常映射器 class。

public void run(T configuration, Environment environment) throws Exception {
  environment.jersey().register(ConstraintViolationExceptionMapper.class);
}

这是 dropwizard 0.8 中的编程解决方案:

public void run(final MyConfiguration config, final Environment env) {
    AbstractServerFactory sf = (AbstractServerFactory) config.getServerFactory();
    // disable all default exception mappers
    sf.setRegisterDefaultExceptionMappers(false);
    // register your own ConstraintViolationException mapper
    env.jersey().register(MyConstraintViolationExceptionMapper.class)
    // restore other default exception mappers
    env.jersey().register(new LoggingExceptionMapper<Throwable>() {});
    env.jersey().register(new JsonProcessingExceptionMapper());
    env.jersey().register(new EarlyEofExceptionMapper());
} 

我认为它比配置文件更可靠。如您所见,它还支持所有其他 default exception mappers.

@ValidationMethod 在这里应该有用。不是吗?

http://www.dropwizard.io/0.9.0/docs/manual/validation.html

@ValidationMethod(message="Password cannot be empty")
@JsonIgnore
public boolean isPasswordProvided() {
    return false if password not provided;
}