# LAB-5542: Project Jersey: Building RESTful Web Services in Java

Expected Duration: 120 minutes
Contacts: Martin Matula, Srinivas Bhimisetty

Introduction | Exercise 0 | Exercise 1 | Exercise 2 | Exercise 3 | Summary
Introduction Background Information Steps to Follow Summary ## Exercise 1: Hello world! (20 minutes) This excercise provides a quick introduction into the basics of the JAX-RS/Jersey programming model. For more details, please see the Jersey Tutorial available on the web. In this lesson we are going to build a very basic "Hello world" type of RESTful web service. It will provide an introduction to how you can quickly get started building RESTful sevices using Jersey. You will see the basic concepts of the JAX-RS/Jersey programming model. ### Background Information #### What are RESTful Web Services? RESTful web services are services that are built to work best on the web. Representational State Transfer (REST) is an architectural style that specifies constraints, such as the uniform interface, that if applied to a web service induce desirable properties, such as performance, scalability, and modifiability, that enable services to work best on the Web. In the REST architectural style, data and functionality are considered resources, and these resources are accessed using Uniform Resource Identifiers (URIs), typically links on the web. The resources are acted upon by using a set of simple, well-defined operations. The REST architectural style constrains an architecture to a client-server architecture, and is designed to use a stateless communication protocol, typically HTTP. In the REST architecture style, clients and servers exchange representations of resources using a standardized interface and protocol. These principles encourages RESTful applications to be simple, lightweight, and have high performance. RESTful web services typically map the four main HTTP methods to the operations they perform : create, retrieve, update, and delete. The following table shows a mapping of HTTP methods to the operations they perform.
HTTP Method | Operations Performed
--- | ---
GET | Get a resource
POST | Create a resource or other operations as it has no defined semantics
PUT | Create or update a resource
DELETE | Delete a resource
#### Introducing Project Jersey Project Jersey is an open source, production quality reference implementation for JSR 311: JAX-RS: The Java API for RESTful Web Services. It implements support for the annotations defined in JSR-311, making it easy for developers to build RESTful web services with Java and the Java VM. Jersey also adds additional features not specified by the JSR. The goals and philosophy of Project Jersey are to: To make it very easy and straightforward to build RESTful web services and clients using Java and possibly other Java VM based languages. Track the JAX-RS API and deliver a production quality reference implementation. Provide value-add features on top of the JAX-RS specification. Expose APIs/SPIs to extend Jersey. In this exercise we're going to see what it takes to build a new RESTful web service from scratch using Jersey. NOTE: To be able to provide clear steps, we are using NetBeans to develop this lab. Anyway, all that we are going to show can easily be achieved without NetBeans, using a simple text editor or some other IDE. To demonstrate this, for operations other than creating and editing java files we provide simple instructions on how to do the same thing directly on the command line. ### Steps to Follow Step 1: Creating a New Project If NetBeans is not already running, start it. When NetBeans has started, select File->New Project. In the New Project wizard, select Maven->Maven Project and click Next. Expand "Archetypes from remote Maven Repositories", select "Jersey Archetype: Web App with WAR packaging" and click Next. In the next screen of the wizard, name the project as "jerseyservice" and click the Finish button. NOTE: If this is the first time you are creating a new project based on Jersey maven archetype, it may take more than a minute to create the new project after hitting the Finish button. During this time maven automatically downloads all the necessary dependencies. Without the NetBeans IDE All that we've done so far can easily be done without NetBeans. The steps are equivalent to executing the following on the command line in the directory where you want to create the new project:
    prompt> mvn archetype:generate -DarchetypeCatalog=http://download.java.net/maven/2
        -DinteractiveMode=false -DarchetypeArtifactId=jersey-quickstart-webapp
        -DarchetypeGroupId=com.sun.jersey.archetypes
        -DgroupId=mycompany.com -DartifactId=jerseyservice -Dpackage=com.mycompany
Step 2: Building the Project Now that the new project is created, let's build it. In NetBeans right-click on jerseyservice project - i.e. the new project we've just created - in the Projects tab and choose Build in the pop-up menu. Since this is the very first time we are building a project depending on Jersey libraries, the build may take several minutes. So, in the meantime, we will go ahead to the step 3 and explore the project structure. Without the NetBeans IDE To build the project without NetBeans you can execute the following in the project root directory:
    prompt> mvn install
4. Step 3: Exploring the Project Structure Let's look more closely at how our new project looks like. Expand the Web Pages node and open index.jsp by double-clicking on it. It is a very simple page serving as a starting point for the web application the new project represents. It contains a link to a sample RESTful web service - we call it a resource - that got generated as part of this project, and also a link to the Project Jersey web site. Under Web Pages->WEB-INF open the web.xml file for editing by right-clicking on it and selecting Edit from the pop-up menu. This file is a standard web application deployment descriptor. TROUBLESHOOTING: In case the web.xml file opened in design mode (this can happen if you double-click it instead of right-clicking and choosing Edit), switch to XML editing mode by clicking XML in the editor window. Let's turn on the line numbers in the NetBeans editor to help us navigate through the source code. This can be done by right-clicking on the grey vertical bar on the left side of the editor window and choosing Show Line Numbers in the pop-up menu. Let's look at the interesting portion of the web.xml file:
        3     <servlet>
        4         <servlet-name>Jersey Web Application</servlet-name>
        5         <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
        6         <init-param>
        7             <param-name>com.sun.jersey.config.property.packages</param-name>
        8             <param-value>com.mycompany.jerseyservice</param-value>
        9         </init-param>
       10         <load-on-startup>1</load-on-startup>
       11     </servlet>
       12     <servlet-mapping>
       13         <servlet-name>Jersey Web Application</servlet-name>
       14         <url-pattern>/webresources/*</url-pattern>
       15     </servlet-mapping>
5. Lines 4 and 5 configure `com.sun.jersey.spi.container.servlet.ServletContainer` as the servlet class. This class is an internal class from the Jersey framework that can handle the HTTP requests coming from the clients and route the requests to the implementations of our resources. It knows where too look for the resource classes from the value of `com.sun.jersey.config.property.packages` property. This property is set on lines 7 and 8 of the deployment descriptor to `com.mycompany.jerseyservice`, so Jersey will automatically look for the resource classes in that package and all of the subpackages. Lines 12 to 15 then define a mapping of the servlet to a URL pattern. It tells the server, request to which URLs should be delegated to the Jersey servlet. In this case it is all URLs starting with `/webresources/` right after the application context URL prefix. Expand Source Packages->com.mycompany.jerseyservice and open MyResource.java by double-clicking on it. This is a simple example of a JAX-RS/Jersey resource class. It is a very simple class, just having a single method returning a string. What turns it into a resource are the annotations.
        8 /** Example resource class hosted at the URI path "/myresource"
        9  */
       10 @Path("/myresource")
       11 public class MyResource {
       12
       13     /** Method processing HTTP GET requests, producing "text/plain" MIME media
       14      * type.
       15      * @return String that will be send back as a response of type "text/plain".
       16      */
       17     @GET
       18     @Produces("text/plain")
       19     public String getIt() {
       20         return "Hi there!";
       21     }
       22 }
The `@Path` annotation on line 10 indicates this class is a resource available at path `/myresource` relative to the application servlet URL. The method of this class is annotated by two annotations (lines 17 and 18). The first one - `@GET` - indicates this method should be used to handle HTTP GET requests, the second one - `@Produces` - declares the MIME type of the data the method produces (text/plain in this case). Under Project Files you can see pom.xml. That is the file containing the maven project description. It contains references to all the dependencies based on which maven knows which jars need to be downloaded to build or test the project. More on the pom.xml file format can be found in maven documentation available from maven.apache.org. The file settings.xml is also maven-specific and is out of scope of this lab. Step 4: Running the Project Now that we know how the project looks like and why, let's try to run it. To run the project, we first need to configure it to use GlassFish V2 as the deployment server: In NetBeans, right-click on the project and choose Properties (at the end of the pop-up menu). In the Project Properties dialog select the Run category and set the Server field to GlassFish V2. Also note, the Context Path is set to `/jerseyservice`. To run the project: Right-click on the project and choose Run from the pop-up menu. NetBeans will create a war file containing the compiled project, start GlassFish and use it for deploying the war file. A web browser should be started automatically, once the whole process is done, pointing to `http://localhost:8080/jerseyservice/`. This displays the index.jsp from our project in the browser. "Jersey resource" link points to our resource (MyResource). If we click on it, the browser will automatically send an HTTP GET request to a given URL which will be handled by our resource class - i.e. `getIt()` method will be called which returns a plain text resonse "Hi there!". So, let's click on the link to see if it really works. Without the NetBeans IDE To run the project without NetBeans you can execute the following in the project root directory:
    prompt> mvn install
    prompt> asadmin start-domain
    prompt> asadmin deploy target/jerseyservice.war
3. Step 5: Making Modifications Let's see how we can customize the project a little bit: Rename MyResource.java to HelloResource.java by right-clicking on it in the Projects view and choosing Refactor->Rename from the pop-up menu. Type the new name into the dialog and click Refactor. Open HelloResource.java (if not open yet) and change the URI template (in the `@Path` annotation) for the resource from `/myresource` to `/hello`. Update the comment as well. Rename the `getIt()` method to `getXML()`, change the produced MIME type to text/xml and let the method return "<greeting>Hello world!</greeting>". Update the comments as well. Here is how the resulting class should look like:
       /** Example resource class hosted at the URI path "/hello"
        */
       @Path("/hello")
       public class HelloResource {

           /** Method processing HTTP GET requests, producing "text/xml" MIME media
            * type.
            * @return String that will be send back as a response of type "text/xml".
            */
           @GET
           @Produces("text/xml")
           public String getXML() {
               return "<greeting>Hello world!</greeting>";
           }
       }
4. Since we changed the URI template, we need to update the link to our resource in index.jsp. Open that file and replace line 4 with:
       <p><a href="webresources/hello">Hello resource</a>
Run the application again - NetBeans will build and re-deploy it. We can see it now uses the new URI and the browser recognizes the MIME type of the returned value as XML. ### Summary In this exercise, we explained the basic concepts of REST architectural style and JAX-RS/Jersey programming model. You saw what it takes to create a simple RESTful web application using Jersey. So far, we have been using only the very basic functionality of the Jersey framework. Our resource supported just a single HTTP method - GET, and it did not do much - returned a hardcoded value. In the following exercise we will explore some more advanced server-side features. Back to top Next exercise