jws

JAX-WS Client Example

Hosting a web service is of no use until it becomes usable by a client. In this example we shall learn how to write JAX-WS client for a SOAP web service.

Writing JAX-WS Client is easy. But we shall start our example by first creating a web service and then writing a client for the same.

1. Writing server for web service

1.1 Writing Service Endpoint Interface

First step in writing web service server is to write the interface called Service Endpoint Interface that describes the methods that shall be exposed by web service.

CalculatorI.java

package com.javacodegeeks.examples.jaxws;

import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;

@WebService
@SOAPBinding(style = Style.RPC)
public interface CalculatorI {
	@WebMethod
	int add(int a, int b);

	@WebMethod
	int subtract(int a, int b);

	@WebMethod
	int multiply(int a, int b);

	@WebMethod
	int divide(int a, int b);
}

1.2 Writing Service Implementation Bean

Next step is to write Service Implementation Bean. This is the implementation of Service Endpoint Interface.

CalculatorImpl.java

package com.javacodegeeks.examples.jaxws;

import javax.jws.WebService;

@WebService(endpointInterface = "com.javacodegeeks.examples.jaxws.CalculatorI")
public class CalculatorImpl implements CalculatorI {

	@Override
	public int add(int a, int b) {
		return a + b;
	}

	@Override
	public int subtract(int a, int b) {
		return a - b;
	}

	@Override
	public int multiply(int a, int b) {
		return a * b;
	}

	@Override
	public int divide(int a, int b) {
		return a / b;
	}

}

1.3 Publishing the web service

And now comes the time to publish the web service. Here, we shall be using JAX-WS’s Endpoint API to publish the web service or in other words publish the endpoint.

CalcPublisher.java

package com.javacodegeeks.examples.jaxws;

import javax.xml.ws.Endpoint;

public class CalcPublisher {

	public static void main(String[] args) {
		Endpoint ep = Endpoint.create(new CalculatorImpl());
		ep.publish("http://127.0.0.1:10000/calcServer");
	}

}

In the above program, we are trying to publish the endpoint at URL: http://127.0.0.1:10000/calcServer.

1.4 Verify the web service

To verify if the web service has been properly published, we shall try to access the WSDL file from the browser. The URL shall be like: http://127.0.0.1:10000/calcServer?wsdl.

Upon hitting this URL we will be able to see the WSDL file which describes the web service.

Let’s copy the content of this file into calculator.wsdl.

calculator.wsdl

<!-- Published by JAX-WS RI (http://jax-ws.java.net). RI's version is JAX-WS 
	RI 2.2.9-b130926.1035 svn-revision#5f6196f2b90e9460065a4c2f4e30e065b245e51e. -->
<!-- Generated by JAX-WS RI (http://jax-ws.java.net). RI's version is JAX-WS 
	RI 2.2.9-b130926.1035 svn-revision#5f6196f2b90e9460065a4c2f4e30e065b245e51e. -->
<definitions
	xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
	xmlns:wsp="http://www.w3.org/ns/ws-policy" xmlns:wsp1_2="http://schemas.xmlsoap.org/ws/2004/09/policy"
	xmlns:wsam="http://www.w3.org/2007/05/addressing/metadata" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
	xmlns:tns="http://jaxws.examples.javacodegeeks.com/" xmlns:xsd="http://www.w3.org/2001/XMLSchema"
	xmlns="http://schemas.xmlsoap.org/wsdl/" targetNamespace="http://jaxws.examples.javacodegeeks.com/"
	name="CalculatorImplService">
	<types />
	<message name="add">
		<part name="arg0" type="xsd:int" />
		<part name="arg1" type="xsd:int" />
	</message>
	<message name="addResponse">
		<part name="return" type="xsd:int" />
	</message>
	<message name="divide">
		<part name="arg0" type="xsd:int" />
		<part name="arg1" type="xsd:int" />
	</message>
	<message name="divideResponse">
		<part name="return" type="xsd:int" />
	</message>
	<message name="multiply">
		<part name="arg0" type="xsd:int" />
		<part name="arg1" type="xsd:int" />
	</message>
	<message name="multiplyResponse">
		<part name="return" type="xsd:int" />
	</message>
	<message name="subtract">
		<part name="arg0" type="xsd:int" />
		<part name="arg1" type="xsd:int" />
	</message>
	<message name="subtractResponse">
		<part name="return" type="xsd:int" />
	</message>
	<portType name="CalculatorI">
		<operation name="add" parameterOrder="arg0 arg1">
			<input
				wsam:Action="http://jaxws.examples.javacodegeeks.com/CalculatorI/addRequest"
				message="tns:add" />
			<output
				wsam:Action="http://jaxws.examples.javacodegeeks.com/CalculatorI/addResponse"
				message="tns:addResponse" />
		</operation>
		<operation name="divide" parameterOrder="arg0 arg1">
			<input
				wsam:Action="http://jaxws.examples.javacodegeeks.com/CalculatorI/divideRequest"
				message="tns:divide" />
			<output
				wsam:Action="http://jaxws.examples.javacodegeeks.com/CalculatorI/divideResponse"
				message="tns:divideResponse" />
		</operation>
		<operation name="multiply" parameterOrder="arg0 arg1">
			<input
				wsam:Action="http://jaxws.examples.javacodegeeks.com/CalculatorI/multiplyRequest"
				message="tns:multiply" />
			<output
				wsam:Action="http://jaxws.examples.javacodegeeks.com/CalculatorI/multiplyResponse"
				message="tns:multiplyResponse" />
		</operation>
		<operation name="subtract" parameterOrder="arg0 arg1">
			<input
				wsam:Action="http://jaxws.examples.javacodegeeks.com/CalculatorI/subtractRequest"
				message="tns:subtract" />
			<output
				wsam:Action="http://jaxws.examples.javacodegeeks.com/CalculatorI/subtractResponse"
				message="tns:subtractResponse" />
		</operation>
	</portType>
	<binding name="CalculatorImplPortBinding" type="tns:CalculatorI">
		<soap:binding transport="http://schemas.xmlsoap.org/soap/http"
			style="rpc" />
		<operation name="add">
			<soap:operation soapAction="" />
			<input>
				<soap:body use="literal" namespace="http://jaxws.examples.javacodegeeks.com/" />
			</input>
			<output>
				<soap:body use="literal" namespace="http://jaxws.examples.javacodegeeks.com/" />
			</output>
		</operation>
		<operation name="divide">
			<soap:operation soapAction="" />
			<input>
				<soap:body use="literal" namespace="http://jaxws.examples.javacodegeeks.com/" />
			</input>
			<output>
				<soap:body use="literal" namespace="http://jaxws.examples.javacodegeeks.com/" />
			</output>
		</operation>
		<operation name="multiply">
			<soap:operation soapAction="" />
			<input>
				<soap:body use="literal" namespace="http://jaxws.examples.javacodegeeks.com/" />
			</input>
			<output>
				<soap:body use="literal" namespace="http://jaxws.examples.javacodegeeks.com/" />
			</output>
		</operation>
		<operation name="subtract">
			<soap:operation soapAction="" />
			<input>
				<soap:body use="literal" namespace="http://jaxws.examples.javacodegeeks.com/" />
			</input>
			<output>
				<soap:body use="literal" namespace="http://jaxws.examples.javacodegeeks.com/" />
			</output>
		</operation>
	</binding>
	<service name="CalculatorImplService">
		<port name="CalculatorImplPort" binding="tns:CalculatorImplPortBinding">
			<soap:address location="http://127.0.0.1:10000/calcServer" />
		</port>
	</service>
</definitions>

2. Writing JAX-WS Client

2.1 Generating client code from WSDL

The first step to writing JAX-WS Client is to generate client support code. Java provides wsimport utility that helps in generating this client support code using the WSDL document.

On command prompt, enter following command at it will show the usage of this utility:

$wsimport

Now, let’s take the WSDL file that was saved in step 1.4, browse to the saved directory using command prompt, and execute the following command:

$ wsimport -keep -p client calculator.wsdl

Alternatively, we can also specify the URL of WSDL file in the wsimport command:

$ wsimport -keep -p client http://127.0.0.1:10000/calcServer?wsdl

Output of this command shall be like:

parsing WSDL...



Generating code...


Compiling code...

For the above example, it shall generate 2 java source files and 2 compiled files in the subdirectory client.

Generated Client Code
Generated Client Code

Now, let’s breakdown the command that we used to generate client support code. Option -p specifies the java package in which generated files are to be placed, in this case it was client. -keep option is a flag that represents that generated files are to be kept. There are many other options which can be looked into by just writing wsimport in the command prompt as mentioned above.

2.2 Analyzing the client support code

Now let’s see the source files that wsimport has generated for us. After that we shall analyze these.

wsimport generated CalculatorI:

CalculatorI.java

package client;

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.xml.ws.Action;


/**
 * This class was generated by the JAX-WS RI.
 * JAX-WS RI 2.2.9-b130926.1035
 * Generated source version: 2.2
 * 
 */
@WebService(name = "CalculatorI", targetNamespace = "http://jaxws.examples.javacodegeeks.com/")
@SOAPBinding(style = SOAPBinding.Style.RPC)
public interface CalculatorI {


    /**
     * 
     * @param arg1
     * @param arg0
     * @return
     *     returns int
     */
    @WebMethod
    @WebResult(partName = "return")
    @Action(input = "http://jaxws.examples.javacodegeeks.com/CalculatorI/addRequest", output = "http://jaxws.examples.javacodegeeks.com/CalculatorI/addResponse")
    public int add(
        @WebParam(name = "arg0", partName = "arg0")
        int arg0,
        @WebParam(name = "arg1", partName = "arg1")
        int arg1);

    /**
     * 
     * @param arg1
     * @param arg0
     * @return
     *     returns int
     */
    @WebMethod
    @WebResult(partName = "return")
    @Action(input = "http://jaxws.examples.javacodegeeks.com/CalculatorI/divideRequest", output = "http://jaxws.examples.javacodegeeks.com/CalculatorI/divideResponse")
    public int divide(
        @WebParam(name = "arg0", partName = "arg0")
        int arg0,
        @WebParam(name = "arg1", partName = "arg1")
        int arg1);

    /**
     * 
     * @param arg1
     * @param arg0
     * @return
     *     returns int
     */
    @WebMethod
    @WebResult(partName = "return")
    @Action(input = "http://jaxws.examples.javacodegeeks.com/CalculatorI/multiplyRequest", output = "http://jaxws.examples.javacodegeeks.com/CalculatorI/multiplyResponse")
    public int multiply(
        @WebParam(name = "arg0", partName = "arg0")
        int arg0,
        @WebParam(name = "arg1", partName = "arg1")
        int arg1);

    /**
     * 
     * @param arg1
     * @param arg0
     * @return
     *     returns int
     */
    @WebMethod
    @WebResult(partName = "return")
    @Action(input = "http://jaxws.examples.javacodegeeks.com/CalculatorI/subtractRequest", output = "http://jaxws.examples.javacodegeeks.com/CalculatorI/subtractResponse")
    public int subtract(
        @WebParam(name = "arg0", partName = "arg0")
        int arg0,
        @WebParam(name = "arg1", partName = "arg1")
        int arg1);

}

wsimport generated CalculatorImplService:

CalculatorImplService.java

package client;

import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import javax.xml.ws.WebEndpoint;
import javax.xml.ws.WebServiceClient;
import javax.xml.ws.WebServiceException;
import javax.xml.ws.WebServiceFeature;


/**
 * This class was generated by the JAX-WS RI.
 * JAX-WS RI 2.2.9-b130926.1035
 * Generated source version: 2.2
 * 
 */
@WebServiceClient(name = "CalculatorImplService", targetNamespace = "http://jaxws.examples.javacodegeeks.com/", wsdlLocation = "file:/Users/saurabharora123/Downloads/calculator.wsdl")
public class CalculatorImplService
    extends Service
{

    private final static URL CALCULATORIMPLSERVICE_WSDL_LOCATION;
    private final static WebServiceException CALCULATORIMPLSERVICE_EXCEPTION;
    private final static QName CALCULATORIMPLSERVICE_QNAME = new QName("http://jaxws.examples.javacodegeeks.com/", "CalculatorImplService");

    static {
        URL url = null;
        WebServiceException e = null;
        try {
            url = new URL("file:/Users/saurabharora123/Downloads/calculator.wsdl");
        } catch (MalformedURLException ex) {
            e = new WebServiceException(ex);
        }
        CALCULATORIMPLSERVICE_WSDL_LOCATION = url;
        CALCULATORIMPLSERVICE_EXCEPTION = e;
    }

    public CalculatorImplService() {
        super(__getWsdlLocation(), CALCULATORIMPLSERVICE_QNAME);
    }

    public CalculatorImplService(WebServiceFeature... features) {
        super(__getWsdlLocation(), CALCULATORIMPLSERVICE_QNAME, features);
    }

    public CalculatorImplService(URL wsdlLocation) {
        super(wsdlLocation, CALCULATORIMPLSERVICE_QNAME);
    }

    public CalculatorImplService(URL wsdlLocation, WebServiceFeature... features) {
        super(wsdlLocation, CALCULATORIMPLSERVICE_QNAME, features);
    }

    public CalculatorImplService(URL wsdlLocation, QName serviceName) {
        super(wsdlLocation, serviceName);
    }

    public CalculatorImplService(URL wsdlLocation, QName serviceName, WebServiceFeature... features) {
        super(wsdlLocation, serviceName, features);
    }

    /**
     * 
     * @return
     *     returns CalculatorI
     */
    @WebEndpoint(name = "CalculatorImplPort")
    public CalculatorI getCalculatorImplPort() {
        return super.getPort(new QName("http://jaxws.examples.javacodegeeks.com/", "CalculatorImplPort"), CalculatorI.class);
    }

    /**
     * 
     * @param features
     *     A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy.  Supported features not in the features parameter will have their default values.
     * @return
     *     returns CalculatorI
     */
    @WebEndpoint(name = "CalculatorImplPort")
    public CalculatorI getCalculatorImplPort(WebServiceFeature... features) {
        return super.getPort(new QName("http://jaxws.examples.javacodegeeks.com/", "CalculatorImplPort"), CalculatorI.class, features);
    }

    private static URL __getWsdlLocation() {
        if (CALCULATORIMPLSERVICE_EXCEPTION!= null) {
            throw CALCULATORIMPLSERVICE_EXCEPTION;
        }
        return CALCULATORIMPLSERVICE_WSDL_LOCATION;
    }

}

Points to be noted here:

  1. wsimport generated CalculatorI contains the same methods as the original CalculatorI at server side had.
  2. CalculatorImplService has a no-argument constructor that shall construct the Service object.
  3. CalculatorImplService has a method getCalculatorImplPort() that returns instance of CalculatorI on which service methods shall be invoked.

2.3 Invoking the web service

The last step to this tutorial is invoking the web service. To do this let’s first create a new java project and then copy the client support code into it.

You might want to change line#32 in CalculatorImplService that mentions the URL to the HTTP URL instead of file path if you need it. In this case the updated CalculatorImplService shall be like:

CalculatorImplService.java

package client;

import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import javax.xml.ws.WebEndpoint;
import javax.xml.ws.WebServiceClient;
import javax.xml.ws.WebServiceException;
import javax.xml.ws.WebServiceFeature;


/**
 * This class was generated by the JAX-WS RI.
 * JAX-WS RI 2.2.9-b130926.1035
 * Generated source version: 2.2
 * 
 */
@WebServiceClient(name = "CalculatorImplService", targetNamespace = "http://jaxws.examples.javacodegeeks.com/", wsdlLocation = "file:/Users/saurabharora123/Downloads/calculator.wsdl")
public class CalculatorImplService
    extends Service
{

    private final static URL CALCULATORIMPLSERVICE_WSDL_LOCATION;
    private final static WebServiceException CALCULATORIMPLSERVICE_EXCEPTION;
    private final static QName CALCULATORIMPLSERVICE_QNAME = new QName("http://jaxws.examples.javacodegeeks.com/", "CalculatorImplService");

    static {
        URL url = null;
        WebServiceException e = null;
        try {
            url = new URL("http://127.0.0.1:10000/calcServer?wsdl");
        } catch (MalformedURLException ex) {
            e = new WebServiceException(ex);
        }
        CALCULATORIMPLSERVICE_WSDL_LOCATION = url;
        CALCULATORIMPLSERVICE_EXCEPTION = e;
    }

    public CalculatorImplService() {
        super(__getWsdlLocation(), CALCULATORIMPLSERVICE_QNAME);
    }

    public CalculatorImplService(WebServiceFeature... features) {
        super(__getWsdlLocation(), CALCULATORIMPLSERVICE_QNAME, features);
    }

    public CalculatorImplService(URL wsdlLocation) {
        super(wsdlLocation, CALCULATORIMPLSERVICE_QNAME);
    }

    public CalculatorImplService(URL wsdlLocation, WebServiceFeature... features) {
        super(wsdlLocation, CALCULATORIMPLSERVICE_QNAME, features);
    }

    public CalculatorImplService(URL wsdlLocation, QName serviceName) {
        super(wsdlLocation, serviceName);
    }

    public CalculatorImplService(URL wsdlLocation, QName serviceName, WebServiceFeature... features) {
        super(wsdlLocation, serviceName, features);
    }

    /**
     * 
     * @return
     *     returns CalculatorI
     */
    @WebEndpoint(name = "CalculatorImplPort")
    public CalculatorI getCalculatorImplPort() {
        return super.getPort(new QName("http://jaxws.examples.javacodegeeks.com/", "CalculatorImplPort"), CalculatorI.class);
    }

    /**
     * 
     * @param features
     *     A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy.  Supported features not in the features parameter will have their default values.
     * @return
     *     returns CalculatorI
     */
    @WebEndpoint(name = "CalculatorImplPort")
    public CalculatorI getCalculatorImplPort(WebServiceFeature... features) {
        return super.getPort(new QName("http://jaxws.examples.javacodegeeks.com/", "CalculatorImplPort"), CalculatorI.class, features);
    }

    private static URL __getWsdlLocation() {
        if (CALCULATORIMPLSERVICE_EXCEPTION!= null) {
            throw CALCULATORIMPLSERVICE_EXCEPTION;
        }
        return CALCULATORIMPLSERVICE_WSDL_LOCATION;
    }

}

Now we shall write java client that uses wsimport generated artifacts to access the web service.

CalculatorClient.java

package com.javacodegeeks.examples.jaxws.client;

import client.CalculatorI;
import client.CalculatorImplService;

public class CalculatorClient {

	public static void main(String[] args) {
		CalculatorImplService service = new CalculatorImplService();
		CalculatorI calc = service.getCalculatorImplPort();
		
		System.out.println(calc.add(1, 2));
		System.out.println(calc.subtract(2, 2));
		System.out.println(calc.multiply(2, 4));
		System.out.println(calc.divide(6, 3));
	}

}

On running this program, the output shall be like:

3
0
8
2

3. Directory structure of this example

3.1 Directory structure of web service server project

The directory structure of web service server project in eclipse shall look like:

Web Service Server Directory Structure
Web Service Server Directory Structure

3.2 Directory structure of web service client project

The directory structure of web service client project in eclipse shall look like:

Web Service Client Directory Structure
Web Service Client Directory Structure

4. Download the source code

This example has 2 eclipse projects for demonstrating example of JAX-WS Client.

Download the Eclipse project here:

Download
You can download the full source code of this example here: JAX-WS Client Example

Saurabh Arora

Saurabh graduated with an engineering degree in Information Technology from YMCA Institute of Engineering, India. He is SCJP, OCWCD certified and currently working as Technical Lead with one of the biggest service based firms and is involved in projects extensively using Java and JEE technologies. He has worked in E-Commerce, Banking and Telecom domain.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

5 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Satinder SINGH
Satinder SINGH
5 years ago

Nice article! Please advise how to run the server module. Thanks.

Kris
Kris
5 years ago
Reply to  Satinder SINGH

I have same question. How to run server module?

kamal Ladnany
kamal Ladnany
4 years ago

Thank you for this example

fajar
4 years ago

thankyou, very helpful

Venkat Ratnam
Venkat Ratnam
4 years ago

It is very helpful

Back to top button