仅记录 soap 请求和响应 body Jax WS

Logging soap requests and responses body only Jax WS

我在我的项目中使用 JAX-WS 作为网络服务。我想记录这些网络服务的每个请求和响应。目前,我成功记录了每个 request/response,但是出于安全原因我希望删除 header 部分并保留 body,我在我的 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);
        }
    }

这当然会记录每个 request/response,而不区分 header 和正文。我尝试使用 message.getSOAPBody(),但它一直记录 null。

欢迎大家推荐。

PS:这是 return for message.getSOAPBody() is [S:Body: null]

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

 message.getSOAPHeader().detachNode();

下面是代码示例(注意我如何测试 soapHeader 是否为 non-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);
    }
}}