【问题标题】:Jersey 2 status code not visible in HttpServletResponseWrapperJersey 2 状态码在 HttpServletResponseWrapper 中不可见
【发布时间】:2018-03-23 07:19:34
【问题描述】:

Java servlet API 直到 3.0 版才为 HttpServletResponse 提供 getStatus 方法。我创建了一个带有 getStatus 的 HttpServletResponseWrapper 来包装 HttpServletResponse 并在设置状态时捕获它。

这不适用于我的 Jersey 2 servlet。

我的 HttpServletResponseWrapper 是通过我的过滤器的 doFilter(request, wrapperResponse) 传递的。当以 Jersey RESTful Servlet 为端点时,会调用 Filter,但不会调用 getStatus 方法。

有没有我遗漏的配置?

我使用响应生成器返回结果并设置状态。

Response.status(404).build(); Response.status(200).type(mediaType).entity(theEntity).build();

最好的问候 乔辰

【问题讨论】:

  • 您需要HttpServletResponseWrapper 做什么?
  • 要获取 gzip 过滤器的状态代码,404 或 204 响应中没有 gzip 标头。

标签: java jersey servlet-filters http-status-codes servlet-2.5


【解决方案1】:

GZIP 压缩不需要HttpServletResponseWrapper。可以通过来自 JAX-RS 的 WriterInterceptor 来实现:

public class GZIPWriterInterceptor implements WriterInterceptor {

    @Override
    public void aroundWriteTo(WriterInterceptorContext context)
                throws IOException, WebApplicationException {
        final OutputStream outputStream = context.getOutputStream();
        context.setOutputStream(new GZIPOutputStream(outputStream));
        context.proceed();
    }
}

然后在您的ResourceConfig / Application 子类中注册WriterInterceptor

@ApplicationPath("/api")
public class MyApplication extends ResourceConfig {

    public MyApplication() {
        register(GZIPWriterInterceptor.class);
    }
}

要将拦截器绑定到某些资源方法或类,您可以使用name binding annotations

【讨论】:

  • 搞定了。 WriterInterceptor 只有在我发送一个实体时才会触发,所以我的 404 和 204 案例被覆盖了。但是,如果请求没有 Accept-Encoding:gzip, deflate, br 标头,我该如何跳过这个 gzip?
  • @ScubaInstructor 您应该能够使用@Context HttpHeaders httpHeaders 在拦截器中注入请求标头。
  • 我现在将使用这个解决方案 EncodingFilter.enableFor(this, GZipEncoder.class, DeflateEncoder.class);并跳过 WriterInterceptor。
猜你喜欢
  • 2011-08-18
  • 1970-01-01
  • 1970-01-01
  • 2010-10-17
  • 1970-01-01
  • 2020-02-17
  • 1970-01-01
  • 1970-01-01
  • 2016-06-10
相关资源
最近更新 更多