如何使用 CXF 拦截器和 org.w3c.dom.Node 修改 Web 服务请求
使用 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);
}
}
Using a CXF Interceptor I'd like to append some Node to the xml being sent out to the server. I've created a interceptor (see below) that picks up the message as DOM Node, modifies it and writes it back to the message object.
Unfortunately the code does not work as expected - the XML sent to the server does not contain the 'magicWord'. IMHO I'm using the wrong phase for this.
So the question is: how can I modify an outgoing webservice request using the org.w3c.dom.Node syntax?
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);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
最后我自己发现了如何做到这一点。
Finally I've found out myself how to do this.
如果您想在 cxf 拦截器中使用 DOM api 修改请求的正文,正确的阶段是 USER_PROTOCOL
SAAJOutInterceptor 创建 DOM 结构,因此您的拦截器必须在此之后运行,这意味着您可能必须将其添加到拦截器链,因为出于性能原因它并不总是由 cxf 添加。
添加拦截器:
If you want to modify the body of a request using the DOM api in a cxf interceptor the correct Phase is USER_PROTOCOL
The SAAJOutInterceptor creates the DOM structure, so your interceptor must be run after that, this means that you might have to add it to the interceptors chain since it is not always added by cxf for performance reasons.
to add the interceptors: