gpt4 book ai didi

java - Jersey - 使用上下文确定 "@Produces"?

转载 作者:行者123 更新时间:2023-11-30 09:13:49 27 4
gpt4 key购买 nike

我是 Jersey 的新手,想在其他上下文中确定 @Produces 类型,以便在错误处理情况下使用它。

比如我有下面这个生成json的方法:

@Path("test-json")
@Produces(MediaType.APPLICATION_JSON)
@GET
public Object getTestJson(@Context HttpServletRequest req, @Context HttpServletResponse res) throws Exception
{
throw new RuntimeException("POST submitted without CSRF token! ");
}

稍后,在全局异常处理程序中,我想要获取 @Produces 媒体类型。我已经尝试使用类似以下的方法来执行此操作,但是 getMediaType() 返回 null(请注意,这是简化的,但在我的所有测试中 header 都不为 null,只是 getMediaType( ) 为空)。

public class someClass
{
@Context
HttpHeaders headers;

public Response convertExceptionToResponse(T exception)
{
MediaType mediaType = headers.getMediaType();

// At this point, I thought media type would be
// MediaType.APPLICATION_JSON
// for the above 'getTestJson' method, but it's null.
}
}

我该怎么做?

最佳答案

JAX-RS

注入(inject) ResourceInfo并调用 getResourceMethod()这将返回 Java Method .然后您可以简单地检索声明的注释。这里的问题是,如果 @Produces 不是直接位于方法上而是位于层次结构中的某个位置,则使用这种方法您需要进行大量编码。

Jersey 2

注入(inject) ExtendedUriInfo

@Context
private ExtendedUriInfo uriInfo;

并寻找匹配的 ResourceMethod (getMatchedResourceMethod())。然后只需获取可生产媒体类型的列表 ( getProducedTypes() )。

关于java - Jersey - 使用上下文确定 "@Produces"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20846121/

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