How to consume a local SOAP web service (JAX-WS) - Implementation

Lets continue with our example from here and keep things simple and tidy.

Lets say we have a server(A local server for now. ie. localhost). It has a service to add any two numbers. So you have a client who wants to consume that ws. Meaning he frigging needs to add two numbers.

Server side implementation

Add service

You need to have the service now. So write a simple add method in dynamic web project in eclipse. Its is a good idea to add the relevant annotations coz I find it less buggy.
package controller;

import javax.jws.WebMethod;
import javax.jws.WebService;

@WebService(serviceName="MyCalc")
public class Calculator {

 
 @WebMethod
 public int add(int num1, int num2)
 {
  return num1 + num2;
 }
}

WSDL creation

Create a new web service in the same project and create as follows.You can create the WSDL from your add implementation Or you can create the WSDL manually according to add method. ;) 



Deploy and run the web service

Now run the project on the server. Im hoping you have a server created already. And BTW without a server installed you wont be able to create the WSDL even. I have used WildFly 9 to deploy. If all is ok you will be able to see your WSDL at
http://localhost:8080/CalculatorWS/MyCalc?wsdl
[Note: Port and server names can be changed as to how you have configured your sever]

Client implementation

One important thing. Under your web project you -> web content -> wsdl directory you can see your wsdl and its design. So according to following design
MyCalculalator web service is binded to Calculator interface via CalculatorSoapBinding(that little box in the middle). So if we need to access the web service we can access it via Calculator interface which acts as a proxy.

Before we access the web service we need to have our own interface to act as a stub. This stub should also comply with the WSDL also. In a real scenario you ll have to get the WSDL from a UDDI.
So to create the related stubs we will use wsimport tool by JDK.

wsimport -keep http://localhost:8080/CalculatorWS/MyCalc?wsdl
[If you dont add -keep it will generate only .class file and remove the .java files]

Import those files to a normal Java project. So now these stubs are in the controller package.




















Now you can access the WS in the main method. In the command line you can see your service call has been executed.

import controller.Calculator;
import controller.MyCalc;

public class Main {

 public static void main (String args[]) 
 {
  
  // Create a web service instance
  MyCalc mycalc = new MyCalc();
  
  // Access that service with the binded port
  Calculator c = mycalc.getCalculatorPort();
  
  // Consume the service via its interface/proxy
  System.out.println(c.add(54, 87));
  
 
 }
 }
Share:

0 comments: