Monday, December 10, 2012

Hello World for Webservices

I will try to put simple hello world webservice examples here for different implementations.

Before starting with this, we will have the below service common for all.

Interface
package com.helloworld;

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 HelloWorld {
    @WebMethod String sayHello(String name);
}

Implementation
package com.helloworld;

import javax.jws.WebService;

@WebService(endpointInterface = "com.helloworld.HelloWorld")
public class HelloWorldImpl implements HelloWorld {

    @Override
    public String sayHello(String name) {
        return "Hello " + name;
    }
}

Without Container example.
For deploying the service without container.
package com.helloworld;

import javax.xml.ws.Endpoint;

public class HelloWorldPublisher {

    public static void main(String[] args) {
        Endpoint.publish("http://localhost:8080/helloworld/hello", new HelloWorldImpl());
        System.out.println("hello world service published ....");
    }
}

Webservice client
package com.helloworld;

import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;

public class HelloWorldClient {

    public static void main(String[] args) throws MalformedURLException {
        URL url = new URL("http://localhost:8080/helloworld/hello?wsdl");
        QName qname = new QName("http://helloworld.com/", "HelloWorldImplService");
        Service service = Service.create(url, qname);
        HelloWorld hello = service.getPort(HelloWorld.class);
        System.out.println(hello.sayHello("abdullah"));
    }
}

Start the publisher, run the client.
Note we are just using Java 6 no other jars are required.