如何使用 CXF 拦截器和 org.w3c.dom.Node 修改 Web 服务请求

2023-12-14

使用 CXF 拦截器,我想将一些节点附加到发送到服务器的 xml 中。我创建了一个拦截器(见下文),它以 DOM 节点的形式获取消息,修改它并将其写回消息对象。

不幸的是,代码无法按预期工作 - 发送到服务器的 XML 不包含“magicWord”。恕我直言,我为此使用了错误的阶段。

所以问题是:如何使用 org.w3c.dom.Node 语法修改传出的 Web 服务请求?

package dummy;

import org.apache.cxf.message.Message;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

class DummyInterceptor extends AbstractPhaseInterceptor {

    String magicWord = "abc";

    public DummyInterceptor() {
        super(Phase.PRE_PROTOCOL);
    }

    public void handleMessage(Message message) {
        Document document = (Document) message.getContent(Node.class);
        NodeList nodes = document.getElementsByTagName("wsse:Security");
        if (nodes.getLength() == 1) {
            Node wsseSecurityNode = nodes.item(0);
            wsseSecurityNode.appendChild(document.createTextNode(magicWord));
        }
        message.setContent(Node.class, document);
    }
}

最后我自己发现了如何做到这一点。

  • 拦截器必须使用“Phase.PRE_PROTOCOL”
  • 拦截器必须使用 addAfter(SaajOutInterceptor) - SaajOutInterceptor 提供消息中的 Node
  • 拦截器类应该派生自 AbstractSoapInterceptor
  • 拦截器的handleMessage不会做修改DOM本身的肮脏工作,而是使用message.getInterceptorChain().add(...)向消息添加一个新的拦截器。
  • 新添加的拦截器应该修改 DOM
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 CXF 拦截器和 org.w3c.dom.Node 修改 Web 服务请求 的相关文章

随机推荐