Pages

Thursday, March 8, 2012

Java Web Service Client with JAX-WS in Eclipse

In this tutorial, I will show how simple it is to create a web service client that consumes the web service created in the previous blog post. We will be using JAX-WS annotations to inject a reference to the web service in our web service client code. I will be using the Eclipse IDE (Indigo) to  build the web service client.

First let us start by creating a standard Java Project. I will name the project "SimpleCalculatorWebServiceClient". Click finish to allow Eclipse to create the Java Project.





Fire a Terminal or a Command Prompt and cd into the root directory of the project you just created. We will use the wsimport tool to generate the source files and classes you will need to  access the web service. Note that you will need the URL to the web service's WSDL file to execute the wsimport command. Following is the complete wsimport command that will generate all necessary files for you and place them in their respective directories under your Eclipse Java Project.


wsimport -s src/ -d bin/ http://localhost:8089/SimpleCalculatorWebService/CalculatorService?WSDL


Now refresh your project in Eclipse to see all the newly generated files by wsimport. Next, create a new class which will act as the client class. I named this class "CalculatorWSClient". Following is the client's code.

package com.moeabdol;

// jaxws imports
import javax.xml.ws.WebServiceRef;

public class CalculatorWSClient {

 // this is the reference to the web service
 @WebServiceRef(wsdlLocation="http://localhost:8089/CalculatorWebService/CalculatorService?WSDL")
 
 private static CalculatorService service;
 private static Calculator port;
 
 public static void main(String[] args) {
  CalculatorWSClient wsc = new CalculatorWSClient();
  service = new CalculatorService();
  port = service.getCalculatorPort();
  
  System.out.println("10 + 3 = " + port.add(10, 3));
  System.out.println("3 - 10 = " + port.subtract(3, 10));
  System.out.println("100 * 100 = " + port.multiply(100, 100));
  System.out.println("22 / 7 = " + port.divide(22, 7));
 }

}

Right-Click the project and select run as a java application. The results should show in the console window.



No comments :

Post a Comment