The basics of building a RESTful webservice
It's another one of those buzz-words you seem to hear a lot of lately; RESTful webservices. REST stands for REpresentational State Transfer and is an architectural style that can already be found on the Internet since back in the days (the HTTP protocol is an example of a REST system). REST defines resources and representations. Resources can be found using a URI and generally return a representation of the data requested (In XML form, or JSON, or whatever tickles your fancy). There are all sorts of platforms that you can use to implement a REST service in Java, but for this article we'll make our own by abusing the HTTP protocol and using a servlet (which might seem crude, but it get's the idea across).
First let's lay down some principles. A REST application is all about resources. Each resource (user data, a picture, account transactions, etc.) needs at least one URI on which it can be found. There are four methods that a REST application can use, POST (update in SQL), GET (select in SQL), PUT (insert in SQL) and DELETE (delete in SQL). These do exaclty what they say and nothing more, a GET method never updates data. The service doesn't implement a state system (like HTTP does with sessions), clients should keep their own state, if necessary.
Then there's the method of communication, HTTP forms only allow PUT and GET. Even when using AJAX you're stuck with these two, so you need to create a method of communication above the HTTP layer. Let's keep it simple in this example and say that our client is using an AJAX post to send a homemade querystring, containing a set of key-value pairs and the method to use. For example, a querystring could look like this : {GET; country=the Netherlands}. A string like this could be posted to a URI (for example http://www.mywebsite.com/users) where it is parsed. It could then return an XML document to the client containing, for example, all users from the Netherlands. Another example : our querystring look like this {POST, country=the Netherlands}, which is posted to the URI http://www.mywebsite.com/users/Pieter%20Heijman to update the country for the user "Pieter Heijman" to "the Netherlands" (remember, every resource has it's own URI).
So, how do we implement this in Java. In this case, again to keep it simple, we use a servlet. A servlet can be set to react to all URI's in it's domain by setting it in the web.xml file like this :
First let's lay down some principles. A REST application is all about resources. Each resource (user data, a picture, account transactions, etc.) needs at least one URI on which it can be found. There are four methods that a REST application can use, POST (update in SQL), GET (select in SQL), PUT (insert in SQL) and DELETE (delete in SQL). These do exaclty what they say and nothing more, a GET method never updates data. The service doesn't implement a state system (like HTTP does with sessions), clients should keep their own state, if necessary.
Then there's the method of communication, HTTP forms only allow PUT and GET. Even when using AJAX you're stuck with these two, so you need to create a method of communication above the HTTP layer. Let's keep it simple in this example and say that our client is using an AJAX post to send a homemade querystring, containing a set of key-value pairs and the method to use. For example, a querystring could look like this : {GET; country=the Netherlands}. A string like this could be posted to a URI (for example http://www.mywebsite.com/users) where it is parsed. It could then return an XML document to the client containing, for example, all users from the Netherlands. Another example : our querystring look like this {POST, country=the Netherlands}, which is posted to the URI http://www.mywebsite.com/users/Pieter%20Heijman to update the country for the user "Pieter Heijman" to "the Netherlands" (remember, every resource has it's own URI).
So, how do we implement this in Java. In this case, again to keep it simple, we use a servlet. A servlet can be set to react to all URI's in it's domain by setting it in the web.xml file like this :
<servlet>
<servlet-name>service</servlet-name>
<servlet-class>org.example.rest.MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>service</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
This means that, no matter what URL we call in this domain, we always go to our servlet. Our servlet can retrieve our querystring, which we sent it in some way (like with an AJAX call), parse it and create a return message that it returns to the client. And there you have it, REST in it's most crudest and simplest form.
Building a RESTful webservice using JAX-WS
With the basics cleared you might want to know how to make a lightweight REST webservice using JAX-WS. The examples below are built to be running on JBossWeb with native connectors and updated Xalan drivers.
Let's start by looking at what we're going to make. Surprise, surprise, it's the age old "Hello World" application. You can call this service with your name as a parameter and it will return an XML with "Hello [Your name]" in it. Sound easy and let me comfort you, it is easy. The ease of use comes from the annotations and even though I generally believe annotation are overly used, these are brilliant, as you will come to see.
Let's start with our service class file. Let's call it "HelloWorld.java". This class will be the class that responds to the service calls and send the return message. It's sourcecode looks something like this:
package rest.example;
import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.ws.BindingType;
import javax.xml.ws.Provider;
import javax.xml.ws.WebServiceContext;
import javax.xml.ws.WebServiceProvider;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.http.HTTPBinding;
import javax.xml.ws.http.HTTPException;
@WebServiceProvider
@BindingType(value=HTTPBinding.HTTP_BINDING)
public class HelloWorld implements Provider<Source> {
@Resource(type=Object.class)
protected WebServiceContext context;
public Source invoke(Source source) {
try {
MessageContext mc = context.getMessageContext();
String q = (String)mc.get(MessageContext.QUERY_STRING);
String p = (String)mc.get(MessageContext.PATH_INFO);
if (q != null && q.contains("name=")) {
return sayHello(q);
} else if (p != null && p.contains("/name")) {
return sayHello(p);
} else {
return sayHello("Unknown");
}
} catch(Exception e) {
e.printStackTrace();
throw new HTTPException(500);
}
}
private Source sayHello(String name) {
Source source = new StreamSource(
new ByteArrayInputStream((new String("<result>Hello "+name+"</result>")).getBytes()));
return source;
}
}
And that's really all there is to it, the only thing remaining is deploying the code. We take our web.xml and add the following.
<listener>
<listener-class>com.sun.xml.ws.transport.http.servlet.WSServletContextListener</listener-class>
</listener>
<servlet>
<servlet-name>helloWorld</servlet-name>
<servlet-class>com.sun.xml.ws.transport.http.servlet.WSServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>helloWorld</servlet-name>
<url-pattern>/hello/*</url-pattern>
</servlet-mapping>
Next to the additions, add the sun-jaxws.xml file to your WEB-INF folder. It's content describes which class is bound to the servlet.
<?xml version="1.0" encoding="UTF-8"?>
<endpoints xmlns="http://java.sun.com/xml/ns/jax-ws/ri/runtime" version="2.0">
<endpoint name="helloWorld" implementation="rest.example.HelloWorld" url-pattern="/hello/*" />
</endpoints>
If you deploy this in your application server and call it's url you can either add "/hello/name/Pieter%20Heijman" or "?name=Pieter%20Heijman" to access it.






Vignesh V
Invite as author
Nice article !!
Regards
Vignesh