如何在Java中使用SOAP返回多个值(javax.jws)

时间:2015-04-08 09:39:36

标签: java web-services soap

我使用Java 8和Eclipse与TomCat 8。 我想编写一个SOAP Web服务,返回3个整数,每个整数都有不同的字段名称(id,key和value),如下所示:

    <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <soapenv:Body>
      <getArrResponse xmlns="http://DefaultNamespace">
         <id>1</id>
         <key>1</key>
         <value>2</value>
      </getArrResponse>
   </soapenv:Body>
</soapenv:Envelope>

我用Java编写了这个SOAP服务器,它可以工作:

    @WebService()
public class MyWebService {

    @WebMethod(operationName = "printName")
    public String printName(@WebParam(name = "userName") String userName) {

        return "hello " + userName;
    }

    @WebMethod
    public int[] getArr() {
        int[] i = { 1, 1, 2};
        return i;
    }
}

它返回:

    <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <soapenv:Body>
      <getArrResponse xmlns="http://DefaultNamespace">
         <getArrReturn>1</getArrReturn>
         <getArrReturn>1</getArrReturn>
         <getArrReturn>2</getArrReturn>
      </getArrResponse>
   </soapenv:Body>
</soapenv:Envelope>

但我不知道,我也没有找到如何将 getArrReturn 中的字段名称更改为 id key

编辑: 我试图返回一个HashTable对象,然后返回:

    <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <soapenv:Body>
      <getArrResponse xmlns="http://DefaultNamespace">
         <getArrReturn>
            <item xmlns:ns1="http://xml.apache.org/xml-soap" xmlns="">
               <key xsi:type="xsd:string">key</key>
               <value xsi:type="xsd:int">1</value>
            </item>
            <item xmlns="">
               <key xsi:type="xsd:string">value</key>
               <value xsi:type="xsd:int">2</value>
            </item>
            <item xmlns="">
               <key xsi:type="xsd:string">id</key>
               <value xsi:type="xsd:int">1</value>
            </item>
         </getArrReturn>
      </getArrResponse>
   </soapenv:Body>
</soapenv:Envelope>

1 个答案:

答案 0 :(得分:0)

您应该尝试创建并返回一个带有JAXB注释的类:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "context",
    "key",
    "value"
})
@XmlRootElement(name = "getArrResponse")
public class GetArrResponse implements Serializable
{
    private final static long serialVersionUID = 1L;
    @XmlElement(name = "id", required = true)
    private int id;
    @XmlElement(name = "key", required = true)
    private int key;
    @XmlElement(name = "value", required = true)
    private int value;
}

通常从XSD生成此类更方便,如果您要创建更复杂的服务,请考虑这一点。