Returning multiple values from a web service
By: Emiley J Printer Friendly Format
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;
}
}
Most Viewed Articles (in WebServices ) |
Latest Articles (in WebServices) |
Comment on this tutorial
- Data Science
- Android
- AJAX
- ASP.net
- C
- C++
- C#
- Cocoa
- Cloud Computing
- HTML5
- Java
- Javascript
- JSF
- JSP
- J2ME
- Java Beans
- EJB
- JDBC
- Linux
- Mac OS X
- iPhone
- MySQL
- Office 365
- Perl
- PHP
- Python
- Ruby
- VB.net
- Hibernate
- Struts
- SAP
- Trends
- Tech Reviews
- WebServices
- XML
- Certification
- Interview
categories
Subscribe to Tutorials
Related Tutorials
Archived Comments
1. I'm coding a webservice and this is exactly what I
View Tutorial By: Cristian at 2014-11-14 12:52:34
2. Hi, can you please help me on java SOAP code for:<
View Tutorial By: rajan kurunju at 2015-09-29 09:25:56
3. Asking questions are in fact good thing if you are
View Tutorial By: moto agua bombardier gtx at 2017-07-11 06:42:53
4. I constantly spent my half an hour to read this we
View Tutorial By: alquiler barcos mallorca por horas at 2017-07-28 21:03:28