对于 Apache CXF,最好的方法是使用特定于 CXF 实现的拦截器。下面是一个示例自定义拦截器类。
package com.company.app.interceptor;
import javax.xml.namespace.QName;
import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.binding.soap.interceptor.AbstractSoapInterceptor;
import org.apache.cxf.headers.Header;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.phase.Phase;
import org.apache.log4j.Logger;
import org.w3c.dom.Element;
public class SOAPHeaderInterceptor extends AbstractSoapInterceptor {
private static Logger logger = Logger.getLogger(SOAPHeaderInterceptor.class);
public SOAPHeaderInterceptor() {
super(Phase.USER_PROTOCOL);
}
@Override
public void handleMessage(SoapMessage message) throws Fault {
try {
Header fromHeader = message.getHeader(new QName("http://www.w3.org/2005/08/addressing", "From"));
Header messageIdHeader = message.getHeader(new QName("http://www.w3.org/2005/08/addressing", "MessageID"));
String from = null;
if (fromHeader != null && fromHeader.getObject() != null) {
from = ((Element)fromHeader.getObject()).getTextContent();
}
String messageId = null;
if (messageIdHeader != null && messageIdHeader.getObject() != null) {
messageId = ((Element)messageIdHeader.getObject()).getTextContent();
}
} catch (Exception e) {
logger.error("Unable to read SOAP Headers", e);
}
}
}
然后,在您的 JAX-WS 服务实现类中指定 @InInterceptors 注释。
@InInterceptors(interceptors ="com.company.app.interceptor.SOAPHeaderInterceptor")