仅记录SOAP请求和响应主体Jax WS

时间:2015-02-23 14:55:00

标签: web-services soap jax-ws

我在项目中使用JAX-WS作为webservices。我想记录这些Web服务的每个请求和响应。暂时,我成功记录了每个请求/响应,但是为了安全起见我希望删除标题部分并保留正文,我在我的SOAPHandler中使用此方法在应用程序日志中写入:

private void logToSystemOut(SOAPMessageContext smc) {
        Logger logger = Logger.getLogger(LogHandler.class);
        Boolean outboundProperty = (Boolean) smc
                .get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
        if (outboundProperty.booleanValue()) {
            logger.info("Outbound message:");
        } else {
            logger.info("Inbound message:");
        }

        SOAPMessage message = smc.getMessage();
        try {
            Source source = message.getSOAPPart().getContent();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            Transformer transformer = TransformerFactory.newInstance()
                    .newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty(
                    "{http://xml.apache.org/xslt}indent-amount", "3"); 
            transformer.transform(source, new StreamResult(baos));
            logger.info(baos.toString());
        } catch (Exception e) {
            logger.warn("Exception in handler: " + e);
        }
    }

这当然记录每个请求/响应,而不区分标题和正文。我尝试使用message.getSOAPBody(),但它一直记录为null。

欢迎所有推荐。

PS:这是message.getSOAPBody()的返回[S:Body:null]

1 个答案:

答案 0 :(得分:2)

我已成功解决了使用SOAP头的detachnode方法的问题,如下所示:

 message.getSOAPHeader().detachNode();

这里是代码如何变成的代码示例(请注意我如何测试soapHeader是否为非null,否则它会抛出空指针异常):

    private void logToSystemOut(SOAPMessageContext smc) {
    Logger logger = Logger.getLogger(LogHandler.class);
    Boolean outboundProperty = (Boolean) smc
            .get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
    if (outboundProperty.booleanValue()) {
        logger.info("Outbound message:");
    } else {
        logger.info("Inbound message:");
    }

    SOAPMessage message = smc.getMessage();
    try {
        if(message.getSOAPHeader()!=null)
        message.getSOAPHeader().detachNode();
        Source source = message.getSOAPPart().getContent();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "3"); 
        transformer.transform(source, new StreamResult(baos));
        logger.info(baos.toString());
    } catch (Exception e) {
        logger.warn("Exception in handler: " + e);
    }
}}