2015-06-09 184 views
0

我正在寫jax-rs端點。對於一些端點集(現有代碼),我想設置一個額外的響應頭,它實際上是在@AroundInvoke攔截器中生成的,並設置爲HttpServletRequest屬性。在@AroundInvoke中,我可以使用@Inject訪問HttpServletRequest。但似乎我不能在同一個攔截器本身中訪問HttpServletResponse。使用攔截器設置響應頭?

看來我可以用PostProcessorInterceptor做,但我又對以下文檔感到困惑。

org.jboss.resteasy.spi.interception.PostProcessInterceptor在調用JAX-RS方法但在MessageBodyWriters被調用之前運行。它們只能在服務器端使用。如果您需要設置響應標頭,則可能沒有任何MessageBodyWriter被調用

我正在使用resteasy,傑克遜。如果我使用PostProcessorInterceptor,我可以注入HttpServletResponse嗎?或者我可以在那裏設置新的HTTP標頭嗎?

任何代碼示例/方向,將不勝感激。

+0

什麼JavaEE的版本是你的工作? –

+0

我不確定...因爲它已預先配置。有沒有什麼簡單的方法可以在eclipse中查找?我們正在使用wildfly 8.0,我猜這是java ee 7 – pinkpanther

回答

1

隨着JAXRS 2(附帶的JavaEE 7)你可以使用一個ContainerResponseFiltersee also

public class PoweredByResponseFilter implements ContainerResponseFilter { 

    @Inject 
    HttpServletRequest request; 

    @Override 
    public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) 
     throws IOException { 
      String name = "X-My-Header"; 
      String value = "";// some data from request 
      responseContext.getHeaders().add(name, value); 
    } 
} 
+0

PostProcessorInterceptor已被棄用,現在應該用這個來替代那個? – pinkpanther

+0

你能回答這個http://stackoverflow.com/questions/30731511/how-to-use-the-same-containerrequestfilter-for-multiple-projects? – pinkpanther

+0

@pinkpanther當你想修改標題過濾器比攔截器更好。 – mkrakhin