java - 更改 JAX-WS 默认 XML 命名空间前缀

标签 java jax-ws

我已经使用 JAX-WS 2.1.7 为旧的 Web 服务生成了源代码。当我调用此服务时,生成的 soap 消息是这样的:

<env:Envelope xmlns:env='http://schemas.xmlsoap.org/soap/envelope/'>
  <env:Header>
  </env:Header>
  <env:Body>
      ...
  </env:Body>
</env:Envelope>

但是旧的网络服务只接受这种格式:

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    ...
  </soap:Body>
</soap:Envelope>

如您所见,前缀是“soap”而不是“env”,并且没有 header ,所以我收到一个错误,提示需要“soap:Body”。我无法更改旧的 Web 服务,需要发送兼容的 soap 消息。如何将前缀更改为“soap”并删除“Header”?

最佳答案

您需要创建一个实现 SOAPHandler<SOAPMessageContext> 的类这包括这样的事情:

  public boolean handleMessage(final SOAPMessageContext context)
  {
    final Boolean isSoapResponse = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
    if (!isSoapResponse)
    {
      try
      {
        final SOAPMessage soapMsg = context.getMessage();
        soapMsg.getSOAPPart().getEnvelope().setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:soap", "http://schemas.xmlsoap.org/soap/envelope/");
        soapMsg.getSOAPPart().getEnvelope().removeAttributeNS("http://schemas.xmlsoap.org/soap/envelope/", "env");
        soapMsg.getSOAPPart().getEnvelope().removeAttribute("xmlns:env");
        soapMsg.getSOAPPart().getEnvelope().setPrefix("soap");
        soapMsg.getSOAPBody().setPrefix("soap");
        soapMsg.getSOAPPart().getEnvelope().getHeader().detachNode();
      }
      catch (SOAPException e)
      {
        e.printStackTrace();
      }
    }
    return true;
  }

然后创建一个handler.xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<handler-chains xmlns="http://java.sun.com/xml/ns/javaee">
  <handler-chain>
    <handler>
      <handler-name>test.MySoapHandler</handler-name>
      <handler-class>test.MySoapHandler</handler-class>
    </handler>
  </handler-chain>
</handler-chains>

并为您的网络服务添加注释:

@HandlerChain(file = "handler.xml")

关于java - 更改 JAX-WS 默认 XML 命名空间前缀,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10678723/

相关文章:

java - Apache CXF 格式错误的消息异常

java - JAX-WS 无法在 OSGI 环境中解码

JavaME MIDlet 不会清除变量吗?

Java runOnUiThread 和 Thread.sleep

java - 将精确距离添加到 GPS 坐标

c# - DDD 和 “Onion Architecture” 是什么关系?

java - 学习 Java Web 服务细节的资源?

java - WSContext.getUserPrincipal() 为密码摘要认证返回 null

java - 尝试从 Android 数据库中获取数据时 JSON 显示错误 403

java - 使用 Java 中的有限库创建 Excel 文件