Returning multiple values from a web service
By: Emiley J
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;
}
}
Archived Comments
1. I constantly spent my half an hour to read this web site's content
all the time along with a
View Tutorial By: alquiler barcos mallorca por horas at 2017-07-28 21:03:28
2. Asking questions are in fact good thing if you are not understanding anything entirely, but this pie
View Tutorial By: moto agua bombardier gtx at 2017-07-11 06:42:53
3. Hi, can you please help me on java SOAP code for:
request parameters: name, class, rollnumber
View Tutorial By: rajan kurunju at 2015-09-29 09:25:56
4. I'm coding a webservice and this is exactly what I'm looking for.
I have coded an example as
View Tutorial By: Cristian at 2014-11-14 12:52:34
Most Viewed Articles (in WebServices ) |
Latest Articles (in WebServices) |
Comment on this tutorial