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

时间:2012-05-21 01:50:03

标签: 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>

但旧的Web服务只接受这种格式:

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

正如你所看到的前缀是“soap”而不是“env”并且没有标题所以我得到一个错误抱怨“soap:Body”是必需的。我无法更改旧的Web服务,需要发送兼容的soap消息。如何将前缀更改为“soap”并删除“Header”?

1 个答案:

答案 0 :(得分:4)

您需要创建一个实现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")