Sunday, November 17, 2013

Implementing REST services with Java Jersey and Apache Tomcat - Server Side

This is a multi-part discussion on how to implement RESTful web services interfaces using Java using the Jersey API.

Jersey is an JAX-RS API (JSR 311) that makes creation of REST services fairly straight forward.  Jersey is implemented as a servlet; hence you'll need a servlet container to utilize Jersey.  Tomcat is one such container and what we'll be using here.  I'll be using Eclipse as the Java IDE and the embedded Tomcat instance in that IDE.

In Eclipse, create a new 'Dynamic Web Project'.
     
Download the Jersey API and add it your Java Build Path in Project Properties.
    Add <servlet> and <servlet-mapping> entries to the  web.xml file (WEB-INF folder).   
    <servlet>
        <servlet-name>Jersey REST Service</servlet-name>
        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
        <init-param>
          <param-name>com.sun.jersey.config.property.packages</param-name>
          <param-value>com.jwisoft.ctispan.server</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
      </servlet>  
    <servlet-mapping> <servlet-name>Jersey REST Service</servlet-name>
        <url-pattern>/rest/*</url-pattern>
      </servlet-mapping>
    Write your Java functions that will correspond to HTTP verbs (GET, POST, etc).  Jersey utilizes annotations to specify the path and HTTP method a Java function implements (among other things).  The example below provides a retrieval (GET) function for a simple in-memory cache:
    @GET
    @Path("/key/{key}")
        public Response getValue(@PathParam("key") String key)
        {
            logger.debug("Entering getValue(key= " + key + ")");
            InMemCache cache = (InMemCache) context.getAttribute("cache");
            String value = cache.getValue(key);
            Response response = null;
           
            if (value != null)
                response = Response.status(Response.Status.OK).type(MediaType.TEXT_PLAIN).entity(value).build();
            else
                response = Response.status(Response.Status.NOT_FOUND).build();
           
            logger.debug("Exiting getValue(), response= " + response);
            return response;
        }  
     
    Explanation:
    @GET - this annotation means this method is what will be called for a HTTP GET for the URL path as described below.
    @Path  - this annotation signifies the URL path that will invoke this Java method.  Braces "{}" identify query params.
    @PathParam - this annotations identifies the query params from the HTTP request. 
    The 'Response' lines of code build up a '200 OK' or '404 Not Found' HTTP response, depending on whether key is in the cache or not.
     
     

No comments:

Post a Comment