【问题标题】:Jersey - Determine "@Produces" using Context?Jersey - 使用上下文确定“@Produces”?
【发布时间】:2013-12-30 19:27:57
【问题描述】:

我是 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(请注意,这是简化的,但在我的所有测试中标题都不为 null,只是 getMediaType() 为 null)。

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. 
    }
}

我该怎么做?

【问题讨论】:

    标签: java http-headers jersey


    【解决方案1】:

    JAX-RS

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

    球衣 2

    注入ExtendedUriInfo

    @Context
    private ExtendedUriInfo uriInfo;
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-31
      • 2013-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-20
      • 1970-01-01
      相关资源
      最近更新 更多