September 22, 2013

RESTful Web Services on JBossAS 7

Deploying RESTful web services on JBossAS 7 is relatively painless and straightforward. Thanks to the extensive support of annotations vs configuration in JEE 6, creating RESTful web services is almost XML-free.

Let’s start with the good stuff: the code you want to run as a web service. We will use as an example a web service supplying random number as inspired by the classic xkcd comic:


public class RandomResource
    public String xkcd()
        // Chosen by a fair dice roll
        // Guaranteed to be random
        return "4";

Here we have assigned paths both to the entire class and the specific method. That means the resource will be available at the path "random/xkcd" relative to the path for RESTful web services (more details on that to follow).

From here we can go in two directions: supply an implementation of and let our web services be found automatically or configure a bunch of things in the web.xml. We’ll take the easy way:


public class RestApplication extends Application

Note that we do not override the methods in The specification indicates that the default implementation will return empty sets; furthermore if an implementation of Application returns empty sets then all root resource classes and providers in the WAR will be included. Which is all a fancy way of saying that this is exactly what we want: the container will scan the WAR and find all the resource classes by annotation.

Notice we used the ApplicationPath annotation; this tells the container the root URI for RESTful web services. So our xkcd() method now has URI "jaxrs/random/xkcd" relative to the deployment of the WAR.

Finally we have the small piece of XML necessary. We need to include a web.xml file in order to indicate that we are using servlet version 3.0. If all we have are the RESTful web services in the application, the web.xml can be empty aside from the root element:

<web-app xmlns=""

OK, now we are ready to package it up and deploy to JBossAS 7. We are going to create a WAR file named rest.war. Just to refresh your memory, the Java classes are compiled and placed in the WEB-INF/classes directory and the web.xml is placed in the WEB-INF directory. You may also want to include a "Hello world" HTML file in the WAR as well for debugging.

Copy the rest.war file into the $JBOSS_HOME/standalone/deployments directory and start JBoss if you have not already. Now you can get a random number (xkcd-style) via the URL http://localhost:8080/rest/jaxrs/random/xkcd.


No comments:

Post a Comment

Note: Only a member of this blog may post a comment.