2017-10-11 113 views
0

Java servlet API在版本3.0之前不爲HttpServletResponse提供getStatus方法。我創建了一個包含getStatus的HttpServletResponseWrapper來封裝HttpServletResponse並在設置時捕獲狀態。Jersey 2狀態代碼在HttpServletResponseWrapper中不可見

這不適用於我的Jersey 2 servlet。

我的HttpServletResponseWrapper通過我的過濾器的doFilter(request,wrapperResponse)傳遞。 Filter被調用,但當Jersey RESTful Servlet是端點時,getStatus方法不會被調用。

有沒有我錯過的配置?

我使用響應構建器來返回結果並設置狀態。

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

問候 約亨

+0

你需要一個'HttpServletResponseWrapper'來做什麼? –

+0

要獲取gzip過濾器的狀態碼,請在404或204響應中不使用gzip標頭。 – ScubaInstructor

回答

0

你並不需要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

+0

得到它的工作。 WriterInterceptor只在我發送一個實體時才觸發,因此我的404和204情況被覆蓋了。但是如果請求沒有Accept-Encoding,我怎麼能跳過這個gzip:gzip,deflate,br header? – ScubaInstructor

+0

@ScubaInstructor您應該可以使用'@Context HttpHeaders httpHeaders'在攔截器中注入請求標頭。 –

+0

我現在要用這個解決方案EncodingFilter.enableFor(this,GZipEncoder.class,DeflateEncoder.class);並跳過WriterInterceptor。 – ScubaInstructor