Tuesday, March 15, 2011

Write your first JAXWS web service

Today I'll try to explain how easily one can build a JAX-WS web service. Web Services are very popular now-a-days. They are used every where. But I found it difficult to write my first web service with jax-ws, partly because I was trying myself and partly because I could not get a simple explanation of steps. That is why I'll try to show the simplest web service possible using jaxws.

First thing first, what do you need to build your first jax-ws web service.
  1. JDK 1.6 (I used update 23)
  2. Eclipse IDE (you can use some other IDE as well)
  3. Are you kidding? nothing else.
JAX-WS 2.0 is actually Sun's (now Oracle) reference implementation of Web Service stack. It is bundled with JDK 6 and above.

First you need to create a Java project in Eclipse. Then create a class called com.ws.HelloService. This will be our web service class. Have a public method in this class which will be exposed as web service. Below is the code -


package com.ws;

import javax.jws.WebService;

@WebService
public class HelloService
{
   public String sayHello(String name)
   {
      return ("Hello " + name);
   }
}

The catch here is the @WebService annotation. This is the key. It tells jaxws engine that the HelloService is a web service class. By default jax-ws exposes all public methods of a class. So, in our case it will expose sayHello operation.
Now our service code is ready. It needs to be deployed to some HTTP server for testing. Fortunately, JDK 6 comes with Jakarta Commons HTTP client. We can directly deploy the service in this server. Create a separate class for this -

package com.ws;

import javax.xml.ws.Endpoint;

public class PublishWS
{
   public static void main(String[] args)
   {
      String url = "http://localhost:9999/helloservice";
      HelloService service = new HelloService();
      Endpoint.publish(url, service);
   }
}

Run this class. Thats it. We are done with deployment. You can check the WSDL document at <ws url>?wsdl location. Invoke the service with some name. It will return Hello + name.

2 comments:

  1. If you are putting a document for first time learners, then you have to provide detailed info.

    ReplyDelete
  2. Write some good materials buddy :)

    ReplyDelete