如何将拦截器添加到wsdl2java(CXF)生成的客户端?

时间:2012-08-22 10:23:53

标签: web-services soap cxf

我正在尝试将一些日志记录添加到wsdl2java生成的客户端的入站/出站流量中。 我有客户端生成并使用它如下:

伪代码:

MyService ws = new MyService().getMyServiceSoap12();
((BindingProvider)ws).getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, webServiceAddress); // for dynamic endpoints...

有什么方法可以添加一些拦截器吗?顺便说一下,我在 Spring 应用程序中使用它!

2 个答案:

答案 0 :(得分:1)

我不确定您的问题是询问如何启用内置请求/响应日志记录,还是更换和/或增强现有日志记录功能。

假设前者,我建议您查看CXF User Guide的{​​{3}}和Debugging and Logging部分。最重要的一点是,CXF默认使用 Java SE logging ,这意味着如果你想使用其他东西,你需要在项目中抛出一个SLF4J桥。

要启用日志记录,请在Spring配置中合并这些位(注意cxf名称空间):

<beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:cxf="http://cxf.apache.org/core"
      xsi:schemaLocation="
http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">

    <cxf:bus>
        <cxf:features>
            <cxf:logging/>
        </cxf:features>
    </cxf:bus> 
</beans> 

答案 1 :(得分:0)

如果您需要自定义日志记录或以不同方式处理SOAP消息,您可以实现自己的javax.xml.ws.handler.soap.SOAPHandler,具体方法如下:

MyService ws = new MyService().getMyServiceSoap12();

BindingProvider wsBindingProvider = (BindingProvider) ws;

// Get a copy of the handler chain for a protocol binding instance
List<Handler> handlers =
    wsBindingProvider.getBinding().setHandlerChain();

// Add your handler(s)
handlers.add(new MySoapMessageLogger());

// We need to setHandlerChain because setHandlerChain
// returns a copy of List<Handler>
wsBindingProvider.getBinding().setHandlerChain(handlers);

MySoapMessageLogger可能如下所示:

public class MySoapMessageLogger implements SOAPHandler<SOAPMessageContext> {

    private static final Logger logger = 
        LoggerFactory.getLogger(MySoapMessageLogger.class);

    @Override
    public boolean handleMessage(SOAPMessageContext context) {
        Boolean isRequest = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
        // Retrieve the message contents
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        context.getMessage().writeTo(stream);

        // You've got your XML message and can log it right away or
        // beautify it with some library before sending to log
        logger.trace((isRequest ? "Request:" : "Response:") + stream.toString());

        return true;
    }

    /* For the logging purposes the following methods can be leaved as stubs */

    @Override
    public Set<QName> getHeaders() {
        return null;
    }

    @Override
    public boolean handleFault(SOAPMessageContext context) {
        return false;
    }

    @Override
    public void close(MessageContext context) {
    }
}