我是 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 (请注意,这是简化的,但 headers 在我的所有测试中都不为 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/