覆盖DropWizard ConstraintViolation消息
所以我想通过DropWizard资源更改用于validation模型的validation消息。
我正在使用java beanvalidation注释。 例如,这是我要validation的字段之一:
@NotEmpty(message = "Password must not be empty.")
我可以使用validation器按预期测试它的工作原理。
但是,当我使用DropWizard对资源进行validation时,它会为该消息添加一些额外的内容。 我看到的是这个 – password Password must not be empty. (was null)
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 String format(ConstraintViolation v) { if (v.getConstraintDescriptor().getAnnotation() instanceof ValidationMethod) { final ImmutableList nodes = ImmutableList.copyOf(v.getPropertyPath()); final ImmutableList 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是使用该方法的那个。 要覆盖它,您需要取消注册它并注册您自己的ExceptionMapper 。
删除exception映射器
Dropwizard 0.8
将以下内容添加到yaml文件中。 请注意,它将删除dropwizard添加的所有默认exception映射器。
server: registerDefaultExceptionMappers: false
Dropwizard 0.7.x
environment.jersey().getResourceConfig().getSingletons().removeIf(singleton -> singleton instanceof ConstraintViolationExceptionMapper);
创建并添加自己的exception映射器
public class ConstraintViolationExceptionMapper implements ExceptionMapper { @Override public Response toResponse(ConstraintViolationException exception) { // get the violation errors and return the response you want. } }
并在您的应用程序类中添加您的exception映射器。
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() {}); env.jersey().register(new JsonProcessingExceptionMapper()); env.jersey().register(new EarlyEofExceptionMapper()); }
我认为它比配置文件更可靠。 正如您所看到的,它还可以启用所有其他默认exception映射器 。
@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; }