Wednesday, March 23, 2011

JAX-WS quick tutorial

Prerequirements
  1. JDK 1.6 +
  2. Eclipse
You can source code (2 eclipse projects for client and server) here.

Developing the Webservice End Point


  1. Open eclipse and create a java project "WS-Server"
  2. Create WS-Service Endpoint interface:
    package com.vaani.jaxws.greet.enpoint;

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

    @WebService
    public interface Greeting {
    @WebMethod String sayHello(String name);
    }

    Now create the corresponding implementation:


    package com.vaani.jaxws.greet.enpoint;

    import javax.jws.WebService;

    @WebService(endpointInterface = "com.vaani.jaxws.greet.enpoint")
    public class GreetingImpl implements Greeting {

    @Override
    public String sayHello(String name) {
    return "Hello, Welcom to jax-ws " + name;
    }

    }


  3. Create end point publisher class( having main)


    package com.vaani.jaxws.greet.publisher;

    import javax.xml.ws.Endpoint;

    import com.vaani.jaxws.greet.enpoint.GreetingImpl;


    public class WSPublisher {
    public static void main(String[] args) {
    Endpoint.publish("http://localhost:8080/WS/Greeting",
    new GreetingImpl());
    }
    }



  4. Run the service
    To check whether service is running or not:
    http://localhost:8080/WS/Greeting?wsdl



Developing the WebService Client





  1. Open eclipse and create a java project "WS-Client"
  2. Generate the client-stubs
    a) Browse to the client folder by command prompt
       
    CD %CLIENT_PROJECT_HOME%\src

    b) Use command wsimport :
           It will look something like this:

    Now this will generate 6 java source files and corresponding compiled class files, if you want you can remove these file.
  3. Create client class which uses this service (using generated stubs)


    package com.vaani.jaxws.greet.client;

    import com.vaani.jaxws.greet.enpoint.Greeting;
    import com.vaani.jaxws.greet.enpoint.GreetingImplService;


    public class Client {
    public static void main(String[] args){

    GreetingImplService service = new GreetingImplService();
    Greeting greeting = service.getGreetingImplPort();
    System.out.println("------->> Call Started");
    System.out.println(greeting.sayHello("Kinshuk"));
    System.out.println("------->> Call Ended");
    }
    }


  4. Run the class and you may get output like this:


    ------->>  Call Started
    Hello, Welcom to jax-ws Kinshuk
    ------->> Call Ended


You can download this code here.

No comments:

Post a Comment

Chitika