How-to: Write web services using Axis2 (Part 2)

In my previous post I wrote about writing a web service provider using axis. But I did not mention a few things in that post.

  1. How to make the service accessible to the outside world
  2. How to write a Java client to avail the services

1. How to make the service accessible to the outside world?

As we are using the axis2.war as the way to deploy the services, we don’t really need to do anything. The deployment descriptor (web.xml) of axis2.war is equipped to handle it. But we need to make some URL mapping and stuffs like that.

  • Add appropriate URL-servlet mapping  in the web.xml
  • Add the name of the AAR in the service list

a. Deployment descriptor changes:

 <servlet>
   <servlet-name>AxisServlet</servlet-name>
   <display-name>Apache-Axis Servlet</display-name>
   <servlet-class>org.apache.axis2.transport.http.AxisServlet</servlet-class>
  <load-on-startup>1</load-on-startup>
 </servlet>

 <servlet-mapping>
   <servlet-name>AxisServlet</servlet-name>
   <url-pattern>/servlet/AxisServlet</url-pattern>
 </servlet-mapping>

 <servlet-mapping>
   <servlet-name>AxisServlet</servlet-name>
   <url-pattern>/services/*</url-pattern>
 </servlet-mapping>

b. Add the name of the AAR in WEB-INF/services/services.list.

2. Writing a Java client to access the services

We have several ways to create the client stubs – JiXB, ADB etc. I followed ADB – Axis Data Binding. Axis provides a WSDL2Java tool to create client stubs from an existing WSDL. We can get the WSDL from http://localhost/services/SampleWs?wsdl.

WSDL2Java -uri SampleWs.wsdl -p subin.rnd.ws.client -d adb -s -o clientStubSrcDirectory_name

This will create the stub in the specified directory with name SampleWsStub.java. Once the stub is ready, we can write a client module which tries to access the deployed services.

WsClient.java

package subin.rnd.ws.client;

import subin.rnd.ws.client.SampleWsStub.WsInput;
import subin.rnd.ws.client.SampleWsStub.WsOutput;

public class WsClient
{
 public static void main(String[] args)
 throws Exception
 {
   SampleWsStub stub = new SampleWsStub("http://localhost/services/SampleWs");

   // Send the request
   SampleWsStub.DoSomething request = new SampleWsStub.DoSomething();
   WsInput anInput = new WsInput();
   anInput.setName("subin");
   request.setAnInput(anInput);

   // Get the response
   SampleWsStub.DoSomethingResponse response = stub.doSomething(request);
   WsOutput anOutput = response.get_return();

   System.out.println(anOutput.getResponseString());
 }
}

And that’s it !!!