Returning multiple values from a web service
 


Although this is quite a common requirement, it could be quite a daunting task for a beginner learning web service. I have seen so many questions in various forums regarding this. For example, one popular question is how to return a HashMap from a web service. In this tutorial, I will keep it very simple. I will just return two values from the webservice instead of one.

The trick is to use javax.xml.ws.Holder and define @WebParam as an output parameter in your definition. An example is below.


import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.xml.ws.Holder;


/**
 *
 * @author Emiley
 */

@WebService(serviceName = "TestMultiple")
public class TestMultiple {
    @WebMethod(operationName = "Calculate")
    public void Calculate(@WebParam(name = "sum", mode = WebParam.Mode.OUT) Holder sum,
                               @WebParam(name = "multiply", mode = WebParam.Mode.OUT) Holder multiply) {
       sum.value = 4+5;
       multiply.value = 4*5;
    }
	}

When you call this web service, you will get the following output.

<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
   <S:Body>
      <ns2:operationResponse xmlns:ns2="http://java-samples.com/">
         <sum>9</sum>
         <multiply>20</multiply>
      </ns2:operationResponse>
   </S:Body>
</S:Envelope>

Of course, you can make your web service more useful by adding two parameters to get the values and add them as below


import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.xml.ws.Holder;


/**
 *
 * @author Emiley
 */

@WebService(serviceName = "TestMultiple")
public class TestMultiple {
    @WebMethod(operationName = "Calculate")
    public void Calculate(int x, int y, @WebParam(name = "sum", mode = WebParam.Mode.OUT) Holder sum,
                               @WebParam(name = "multiply", mode = WebParam.Mode.OUT) Holder multiply) {
       sum.value = x+y;
       multiply.value = x*y;
    }
	}

 
 
 
 
 
COPYRIGHT´┐Ż 2006 java-samples.com. ALL RIGHTS RESERVED.