2017-10-12 154 views
0

我有基於Apache CXF的Web服務。我編寫了攔截器來記錄一些包含http響應代碼的特定內容。如何在CXF攔截器中獲取HTTP RESPONSE CODE?

public class MyOutInterceptor extends AbstractPhaseInterceptor<Message> { 

    public MyOutInterceptor() { 
     super(Phase.SEND); 
    } 

    @Override 
    public void handleMessage(Message message) throws Fault { 
     Integer responseCode = (Integer) message.get(Message.RESPONSE_CODE); 
     //... 
    } 
} 

但是!!! responseCodenull。即使我改變攔截器階段,它總是null
如何在CXF攔截器中獲取http響應代碼?


UPD。申請春/ CXF配置:https://gist.github.com/alexiuscrow/b5ceb2df7d652a77cd788454e0792211


UPD。治標不治本

@Override 
public void handleMessage(Message message) throws Fault { 
    Integer responseCode = (Integer) message.get(Message.RESPONSE_CODE); 
    if (null == responseCode) { 
     HttpServletResponseWrapper responseWrapper = 
      (HttpServletResponseWrapper) message.get(AbstractHTTPDestination.HTTP_RESPONSE); 
     responseCode = responseWrapper.getStatus(); 
    } 
    //... 
} 

回答

0

請確保您已註冊的攔截器outinterceptor不是outFaultInterceptor or FaultInterceptor等在這裏被驗證的例子。

import org.apache.cxf.annotations.Provider; 
import org.apache.cxf.annotations.Provider.Type; 
import org.apache.cxf.interceptor.Fault; 
import org.apache.cxf.message.Message; 
import org.apache.cxf.phase.AbstractPhaseInterceptor; 
import org.apache.cxf.phase.Phase; 
import org.slf4j.Logger; 
import org.slf4j.LoggerFactory; 
import org.springframework.stereotype.Component; 

@Component 
@Provider(value=Type.OutInterceptor) 
public class KpOutInterceptor2 extends AbstractPhaseInterceptor<Message> { 

    private final static Logger LOG = LoggerFactory.getLogger(KpOutInterceptor2.class); 

    public KpOutInterceptor2() { 
     super(Phase.SEND); 

    } 

    @Override 
    public void handleMessage(Message message) throws Fault { 
     LOG.info("JAXRS response status code is {}", message.get(Message.RESPONSE_CODE)); 
    } 

} 

或者更好的方式使用JAXRS 2.0標準過濾器。

import java.io.IOException; 

import javax.ws.rs.container.ContainerRequestContext; 
import javax.ws.rs.container.ContainerResponseContext; 
import javax.ws.rs.container.ContainerResponseFilter; 
import javax.ws.rs.ext.Provider; 

import org.slf4j.Logger; 
import org.slf4j.LoggerFactory; 
import org.springframework.stereotype.Component; 

@Component 
@Provider 
public class KpOutInterceptor implements ContainerResponseFilter { 

    private final static Logger LOG = LoggerFactory.getLogger(KpOutInterceptor.class); 

    @Override 
    public void filter(ContainerRequestContext reqCtx, ContainerResponseContext resCtx) throws IOException { 

     LOG.info("JAXRS response status code is {}", resCtx.getStatus()); 

    } 

} 
+0

我檢查了。它綁定到'outInterceptors'。 – Alexiuscrow

+0

檢查第一個解決方案,它與您已經實現的相同,但我想您已經將攔截器註冊到不同的解決方案。 –

+0

攔截器配置有JAX-WS。可能是問題的原因?應用程序Spring/CXF配置:https://gist.github.com/alexiuscrow/b5ceb2df7d652a77cd788454e0792211 – Alexiuscrow