A Web service is a software system identified by a URI whose public interfaces and bindings are defined and described using XML.
Its definition can be discovered by other software systems. These systems may then interact with the Web service in a manner prescribed by its definition, using XML-based messages conveyed by Internet protocols.
There are two major approaches:
Java – to – WSDL (Bottom-Up) : Start with the Java class that implements the service (methods) and from it create the WSDL
WSDL – to – Java (Top-Down) : Start with the WSDL and based on it design the Java interface and implementation
We will use the same Calculator example used for RMI. Similar with the RMI example, we will define a Java interface which describes the Calculator methods (add, subtract, multiply, divide) and a Java implementation class that implements those methods.
public interface Calculator extends Remote { public long subtract(long a, long b) throws java.rmi.RemoteException; public long add(long a, long b) throws java.rmi.RemoteException; public long multiply(long a, long b) throws java.rmi.RemoteException; public long divide(long a, long b) throws java.rmi.RemoteException; } // similar with RMI, the interface extends Remote
public class CalculatorImpl implements Calculator { public CalculatorImpl() { super(); } public long add(long a, long b) throws java.rmi.RemoteException { return a + b; } public long subtract(long a, long b) throws java.rmi.RemoteException { return a - b; } // similar for multiply and divide // unlike in RMI, CalculatorImpl does not extend UnicastRemoteObject
Eclipse automates all phases involved in making a web service accessible to users:
After deployment the web service runs as a web application under the application server (Tomcat)
Similar to a web application, it can be accessed trough a URL. In order to find out the correct URL, open WSDL and look for the correct value for port binding:
<wsdl:port binding="impl:CalculatorImplSoapBinding“ name="CalculatorImpl"> <wsdlsoap:address location="http://localhost:8080/WSServer/services/CalculatorImpl"/> </wsdl:port>
The WSDL can be accessed and displayed remotely appending ?WSDL to the above URL:
http://localhost:8080/WSServer/services/CalculatorImpl?WSDL
A Java client accesses the web service trough a web service stub. The stub is generated from WSDL
The easiest way to create the stub is using Eclipse
Bring a copy of WSDL file under the client project
Right click on WSDL, select Web Services then Generate Client
As a result, several Java classes will be automatically generated
public class CalculatorClient { public static void main(String[] args) { try { CalculatorImplService service = new CalculatorImplServiceLocator(); CalculatorImpl port = service.getCalculatorImpl(); long result = port.add(3, 4); System.out.println("invoked add(3, 4) = " + result); } catch (Exception e) { e.printStackTrace(); } } }