Hug*_*ugo 6 java jax-rs dropwizard
所以我想通过DropWizard资源更改用于验证模型的验证消息.
我正在使用java bean验证注释.例如,这是我要验证的字段之一:
@NotEmpty(message = "Password must not be empty.")
Run Code Online (Sandbox Code Playgroud)
我可以使用验证器按预期测试它的工作原理.
但是,当我使用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());
}
}
Run Code Online (Sandbox Code Playgroud)
有什么办法可以覆盖这种行为吗?我只想显示我在注释中设置的消息...
这是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());
}
Run Code Online (Sandbox Code Playgroud)
我认为它比配置文件更可靠.正如您所看到的,它还支持所有其他默认异常映射器.
ConstraintViolationExceptionMapper是使用该方法的那个.要覆盖它,您需要取消注册它并注册您自己的ExceptionMapper.
删除异常映射器
将以下内容添加到yaml文件中.请注意,它将删除dropwizard添加的所有默认异常映射器.
server:
registerDefaultExceptionMappers: false
Run Code Online (Sandbox Code Playgroud)
environment.jersey().getResourceConfig().getSingletons().removeIf(singleton -> singleton instanceof ConstraintViolationExceptionMapper);
Run Code Online (Sandbox Code Playgroud)
创建并添加自己的异常映射器
public class ConstraintViolationExceptionMapper implements ExceptionMapper<ConstraintViolationException> {
@Override
public Response toResponse(ConstraintViolationException exception) {
// get the violation errors and return the response you want.
}
}
Run Code Online (Sandbox Code Playgroud)
并在您的应用程序类中添加您的异常映射器.
public void run(T configuration, Environment environment) throws Exception {
environment.jersey().register(ConstraintViolationExceptionMapper.class);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2603 次 |
| 最近记录: |