这是我的Web服务方法:
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@POST
@Path("login")
public Response login(@NotNull @Valid Credentials credentials) {
// do login
}
这是客户端代码的片段:
WebTarget loginTarget = baseTarget
.path("base")
.path("login");
Credentials credentials = new Credentials(username, password);
Response resp = loginOperation
.request()
.post(
Entity.entity(credentials, MediaType.APPLICATION_JSON_TYPE)
);
当我发帖时,它没有到达登录方法 . 服务器返回400错误,空体 .
当我从凭证参数中删除 @NotNull @Valid
注释时,它可以正常工作 .
我注意到Entity#entity方法有一个重载版本,它接受 Annotation[]
作为第三个参数 . 然后我遇到了Jersey文档的this section . 所以我按照教程中的建议继续创建了一个注释工厂:
public static class ValidFactory extends AnnotationLiteral<Valid> implements Valid {
public static ValidFactory get() {
return new ValidFactory();
}
}
然后将客户端代码更改为:
.post(
Entity.entity(credentials, MediaType.APPLICATION_JSON_TYPE,
new Annotation[] {
AuthenticationResource.NotNullFactory.get(),
AuthenticationResource.ValidFactory.get()
}
)
)
不幸的是导致了同样的错误 . 谷歌搜索没有产生任何结果,我没有太多时间挖掘 Jersey 的源代码 . 那么,也许知道解决方案的人会分享它,好吗?
UPDATE
只是为了添加@peeskillet的回复 . 我使用自定义ExceptionMapper:
@Provider
public class ValidationExceptionMapper implements ExceptionMapper<ConstraintViolationException> {
@Override
public Response toResponse(ConstraintViolationException exception) {
// customize response
}
}
因此,在我的情况下,我不必设置 ServerProperties.BV_SEND_ERROR_IN_RESPONSE
属性,而是必须在服务器配置中注册映射器:
GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_URI)
new ResourceConfig() {
{
register(ValidationExceptionMapper.class)
}
}
);
1 回答
声音就像你只需configure Jersey to send error messages使用ServerProperties.BV_SEND_ERROR_IN_RESPONSE:
在你的
ResourceConfig
或者在你的web.xml中