gpt4 book ai didi

jersey - 注释 Web 方法参数时,JAX-RS Jersey 客户端获得 400 响应

转载 作者:行者123 更新时间:2023-12-01 08:54:08 25 4
gpt4 key购买 nike

这是我的网络服务方法:

@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[] 作为第三个参数。然后我遇到了this section Jersey 文件。所以我按照教程中的建议继续创建注释工厂:

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()
}
)
)

不幸的是,这导致了同样的错误。谷歌搜索没有产生任何结果,而且我没有太多时间去挖掘泽西源代码。那么,也许知道解决方案的人会分享它吗?

更新

只是为了添加到@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)
}
}
);

最佳答案

听起来你只需要 configure Jersey to send error messages使用 ServerProperties.BV_SEND_ERROR_IN_RESPONSE :

public static final String BV_SEND_ERROR_IN_RESPONSE

A Bean Validation (JSR-349) support customization property. If set to true and Bean Validation support has not been explicitly disabled (see BV_FEATURE_DISABLE), the validation error information will be sent in the entity of the returned Response.

The default value is false. This means that in case of an error response caused by a Bean Validation error, only a status code is sent in the server Response by default.

The name of the configuration property is "jersey.config.beanValidation.enableOutputValidationErrorEntity.server".

在你的 ResourceConfig

property(ServerProperties.BV_SEND_ERROR_IN_RESPONSE, true);

或在您的 web.xml 中

<init-param>
<param-name>
jersey.config.beanValidation.enableOutputValidationErrorEntity.server
</param-name>
<param-value>true</param-value>
</init-param>

关于jersey - 注释 Web 方法参数时,JAX-RS Jersey 客户端获得 400 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31943116/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com