Sunday, March 15, 2009

Building a simple web service for Tomcat in Eclipse using AXIS2

Some time ago I was looking for a very simple basic example of creating web service in Eclipse using Axis2 framework with Tomcat as web server. Unfortunatelly I couldn't find a complete and easy to follow instructions. When I finally manage to build it by myself the idea came to my mind, that it could be usefull to anyone else. So I put this info in my posting.

Prerequisites:

1. Download and install Eclipse IDE for Java EE Developers (current version - ganymede-SR1).
2. Download and install Apache Tomcat (current version 6.0.16).
3. Download and install Apache Axis2 (current version 1.4.1).


Server


1. Start Eclipse.
2. Go to Windows->Preferences->Web Services->Axis2 Preferences.
3. Set Axis2 runtime location.



4. Switch to Servers Tab.
5. Right-Click New->Server.
6. Select Tomcat v6.0 Server



7. Fill the Tomcat installation directory.



8. Click Finish.
9. Check that you can start and stop server.
10. Create new Java Project EchoProject.



11. Click Finish.
12. Create new Java Class EchoServer in the EchoProject project.



13. Click Finish.
14. Type the following code for EchoServer class:

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

@WebService(serviceName="EchoServer", name="EchoServer")
public class EchoServer
{
@WebMethod()
public String echo(String arg)
{
return "Message received: " + arg;
}
}

15. Right-click on EchoServer class and select New->Other from drop-down menu.
16. Select Web Service wizard and click Next.



17. You should get to the following screen.



18. Move the slider to change the level of service generation to “Instal service”.
19. Change Web service runtime to Axis2.



20. Proceed to the end of the dialog.
21. Start server.
22. Check that you can get a WSDL description from the following URL http://localhost:8080/WebServiceProject/services/EchoServer?wsdl
23. Leave this instance of Eclipse running.


Client

1. Start a new instance of Eclipse with different workspace.
2. Create Java Project EchoServiceClient.



3. Click Finish.
4. Right-click on EchoServiceClient class and select New->Other from drop-down menu.
5. Select Web Service Client wizard and click Next.



6. You should get to the following screen.



7. Put the following link as service definition: http://localhost:8080/WebServiceProject/services/EchoServer?wsdl
and click Finish.
8. Create new Java Class EchoClient in the EchoServiceClient project.



9. Click Finish.
10. Type the following code for EchoServer class:

import java.rmi.RemoteException;
import org.apache.ws.axis2.*;

public class EchoClient
{
public static void main(String[] args) throws RemoteException
{
EchoServerPortTypeProxy proxy = new EchoServerPortTypeProxy();
System.out.println(proxy.echo("Hello"));
}
}

11. Start the client.
12. Ignore the warning.
13. The response from server should be : Message received: Hello