Search code examples
javajerseyservlet-filtershttp-status-codesservlet-2.5

Jersey 2 status code not visible in HttpServletResponseWrapper


The Java servlet API does not provide a getStatus method for HttpServletResponse until version 3.0. I have created a HttpServletResponseWrapper with getStatus to wrap HttpServletResponse and catch the status when it is set.

This does not work with my Jersey 2 servlet.

My HttpServletResponseWrapper is passed via the doFilter(request, wrapperResponse) of my Filter. The Filter is called but the getStatus method is not called when a Jersey RESTful Servlet is the endpoint.

Is there any configuration I have missed?

I use the response builder to return the result and set the status.

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

Best Regards Jochen


Solution

  • You don't need a HttpServletResponseWrapper for GZIP compression. It could be achieved with a WriterInterceptor from 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();
        }
    }
    

    Then register the WriterInterceptor in your ResourceConfig / Application subclass:

    @ApplicationPath("/api")
    public class MyApplication extends ResourceConfig {
    
        public MyApplication() {
            register(GZIPWriterInterceptor.class);
        }
    }
    

    To bind the interceptor to certain resource methods or classes, you could use name binding annotations.