Evaluate Weigh the pros and cons of technologies, products and projects you are considering.

Creating and deploying a Jersey-based RESTful Web service

Sun's Jersey project aims to aid developers in creating REST-based Web services. William Brogden digs into the meat of the project for this tutorial on how it works.

In my previous article I found that RESTful Web Service development support based on the Jersey project is available...

as a plugin for NetBeans. Now I want to look at what is involved in creating and deploying a Web service based on the Jersey toolkit. First we need to catch up on the Jersey project.

Jersey and the JSR-311 RESTful Web Service API JSR stands for Java Specification Request, the mechanism used in the Sun sponsored Java Community Process for recruiting expert groups to evolve new Java standards. The product of JSR-311 is the Java API for RESTful Web Services, better known as JAX-RS. The intent of JAX-RS is to provide an API of annotations and related Java classes and interfaces that may be added to POJO (Plain Old Java Object) classes to create a resource class for RESTful Web services

The Jersey project, part of the Sun-sponsored GlassFish group of open source projects, has the task of providing a working reference implementation of JSR-311. In addition to the Java interfaces and classes implementing the API, Jersey provides a servlet that acts as a container for any number of resource classes. Having a working implementation with active users testing it is essential to provide feedback for the expert group working on JSR-311 specification. For example, the user group mailing list frequently contains requests for new features.

Using annotations in Java
Annotations are a special text notation, or metadata, added to Java with version 1.5. Annotations in Java source code can affect both compilation and runtime behavior of the resulting Java classes. The meaning of an annotation is declared in Java code resembling normal Java interface declarations which is compiled. Annotations are increasingly used by designers of programming frameworks as a convenience for programmers and to enforce a programming style. Syntactically, annotations use the @ symbol to start an identifier which the compiler recognizes. There are currently about 40 annotations specified by JSR-311.

How JAX-RS annotations create a resource class
If you are using the NetBeans RESTful Web Service plugin it will assist you in the initial creation of source code containing the minimum annotations required to support REST style requests. Lets look at some examples of annotations - the following @Path annotation added to a class defines the part of a URI which will be used to locate the class and the names of variables that will be extracted from the URI.

@Path( "matching/{domain}/{word}" ) 

So, if the name of my Web application is "MetaPhone", and the Jersey servlet which controls resource classes is mapped to "resources", the URI to request a list of place names phonetically matching "leander" will be:

http://myserver/MetaPhone/resources/matching/Places/leander

As I discuss in detail below, the RESTful application container uses the runtime annotations "GET" and ProduceMime to locate the method best suited to handle a request. In the following code fragment the GET tells the container that this method handles HTTP GET requests and the ProduceMime matches the request header that says HTML output is expected. The PathParam annotations cause the input parameters to be extracted from the Path.

    @GET
    @ProduceMime("text/html")
    public String getHtml(
         @PathParam("domain") String d,
         @PathParam("word") String w 
       ) {

I filled out the getHtml method to use some phonetic lookup code and data I had lying around. The returned String has an HTML-formatted page with the matching words in a list. A nice extension to this project would be to use a PUT method to add new words.

Lifecycle of a RESTful Web application
In Jersey the servlet which supports JAX-RS resources is the ServletAdaptor class in the com.sun.ws.rest.impl.container.servlet package. The deployment descriptor for a RESTful Web service maps this servlet to a name such as "resources" and specifies that it must be initialized when the server (such as Tomcat or GlassFish) is started. On initialization the ServletAdaptor searches for Java classes containing the JAX-RS annotations and inspects them for the HTTP method and Mime type supported. The Jersey project already supports XML and JSON output types in addition to HTML and plain text.

Any number of resource classes supporting various HTTP methods and resource types can be supported in one application. The JAX-WS API gives rules for locating the best match to a request.

When a recognizable URI is forwarded to the ServletAdaptor it uses Java reflection to create an instance of the resource class and uses the annotations embedded in the class to prepare input to the proper method. The output of the selected method becomes the body of the response if any.

It is important to note that each request causes a new instance of a resource class to be created, after the request has been completed, this instance is discarded. Although this extra object creation may sound wasteful, it vastly simplifies the whole process. It is up to the programmer to provide static methods or other classes to hold long-lived data.

Deploying to a servlet container

If you are using NetBeans for development it automatically creates a WAR file containing all libraries and classes needed to support the service by collecting all of the Jersey support library. In my test case this was about 18 files totaling 6.5MB. Deployment to Tomcat, GlassFish or another container follows normal practice.

Deploying to lightweight Web servers
The simplest possible server can be created using the "lightweight Web server" in Sun's release of Java SE 6 as shown in Jersey documentation examples. This provides for receiving HTTP requests, mapping them to the correct method(s) in a single resource server class and returning a HTTP response. One disadvantage of the lightweight server is that all of the library locating functions of typical servlet container are not provided, so it is up to the programmer to include all the JAR files in the classpath.

I found that the Jersey example code for starting the lightweight server as a standalone application has a problem when running in Windows. The example uses a standard Java method call as a simple way to give the operator a way to stop the server:

System.in.read()

This works fine in Unix Java implementations, but freezes the whole program in a Windows Command Prompt. The solution is to let the starting Thread sleep in a loop - (ctrl)C will break the loop and exit the application.

 while( true ){
           try { Thread.sleep(1000);
           }catch(InterruptedException e){}
    } 

My standalone example used less than 3MB to support a simple RESTful service example. The lightweight server could also be embedded in a larger application to provide RESTful access to a single specific resource.

The future of Jersey
The Jersey implementation of JSR-311 is still evolving rather rapidly. The version I used was 0.6ea and version 0.7ea should be available later in April. Fortunately, the NetBeans RESTful Web Services plugin is updated shortly after every release and will be picked up by your normal NetBeans plugin manager. Eventually Jersey will be a production quality reference implementation shipping with the GlassFish Java EE open source server, but I am not about to try to predict when.

Dig Deeper on Topics Archive

Start the conversation

Send me notifications when other members comment.

Please create a username to comment.

-ADS BY GOOGLE

SearchSoftwareQuality

SearchAWS

SearchCloudComputing

TheServerSide.com

Close