4

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

伪代码:

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

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

4

2 回答 2

3

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

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().getHandlerChain();

// 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) {
    }
}
于 2018-05-03T12:17:37.253 回答
1

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

假设是前者,我建议查看CXF User Guide. 最重要的一点是 CXF 默认使用Java SE 日志,这意味着如果你想使用其他东西,你需要在项目中折腾一个 SLF4J 桥。

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

<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> 
于 2012-08-22T22:52:05.863 回答