Skip to content

Minimal Java web services sample.

July 31, 2012

Minimal Java web services sample.

I needed to write small java web service for POC, I normally start step by step using command line keying in source code in vi editor, so that I can even remember the packages and classes in use. Which normally become transparent when we use IDE. I am not undermining IDE in any way they are great and make development real breeze. But while learning new concepts and tools I prefer to start with minimal sample and then build on them later using IDE etc.

Here is minimal java web service Step by step.

1) Write the web service class implementation to keep the sample minimal I am not going to write interface.

package org.ws.hello;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.WebMethod;
@WebService(name="hello")
@SOAPBinding(style=SOAPBinding.Style.RPC)
public class hello {
@WebMethod()
public String hello(){
return "hello world...";
}
}

2) Publish the Web Service using Jdk endpoint.

package org.ws.hello;
import javax.xml.ws.Endpoint;
public class h {
public static void main(String []args){
hello he = new hello();
Endpoint.publish("http://localhost:8000/", he);
}
}

This will start publishing end point on port 8000. You are done for server-side. Now to consume this service we need to generate proxies to communicate with server.

3) Use wsimport utility to generate proxies

wsimport –d <generated source dir> <web service URL>

e.g wsimport -d gen http://localhost:8000/HelloService/hello?wsdl4) Write the client to consume service.

import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.namespace.QName;
import org.ws.hello.Hello;
import org.ws.hello.HelloService;
public class helloClient {
public static void main(String args[]) {
try {
HelloService hs = new HelloService(new URL(
"http://localhost:8000/HelloService/hello?wsdl"),
new QName("http://hello.ws.org/", "helloService"));
Hello h = hs.getHelloPort();
System.out.println(h.hello());
} catch (MalformedURLException e) {
e.printStackTrace();
}
}

That’s it you are done in few steps. For theory you can refer to lot of documentation on the web.

Advertisements

From → Tech

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: