java - Jersey 2 状态代码在 HttpServletResponseWrapper 中不可见

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

直到 3.0 版,Java servlet API 才为 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 压缩。它可以通过 WriterInterceptor 来实现来自 JAX-RS:

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

然后注册 WriterInterceptor在你的ResourceConfig/Application子类:

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

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

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

关于java - Jersey 2 状态代码在 HttpServletResponseWrapper 中不可见,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46691209/

相关文章:

java - 运行深度优先搜索时出现 StackOverflowError(无向图)

java - 我使用 Jersey 生成了 400 响应,但没有得到返回

java - 我应该如何在我的 RESTful JAX-RS Web 服务中记录未捕获的异常?

java - ClassNotFoundException : com. sun.jersey.core.util.FeaturesAndProperties 错误

servlets - 使用Spark Web框架时如何使用 native Servlet筛选器?

java - NumberPicker widget Android 4.0 的使用方法

java - 知道字符集合中是否存在字母的最快方法是什么

java - 错误: incompatible types while using ANT Script

java - 我们是否有任何机制可以使用 Keycloak IDP 的 java servlet 适配器在客户端应用程序上进行注销后 Activity ?

java - 访问 x-www-form-urlencoded ServletRequest 的输入流