REST Web Services in Java

I’ve been taking a look at jersey today. It’s an implementation of JSR 311, which is a proposed spec for implementing REST-like web services in Java. I started with the tutorial, which is quite frankly pretty bloody simple.

  @Path("/helloworld")
  public class HelloWorldResource {
    @GET
    @Produces("text/plain")
    public String getClichedMessage() {
      return "Hello World";
    }
  }

The javadoc for the annotations explains what they do in some more detail (Path, GET, Produces).

The tutorial also includes a method of running that standalone using the grizzly HTTP connector. But I’m a stick-in-the-mud. I want it to run under tomcat. So how do I do that? Again, it turns out to be fairly simple. Just add the jersey-supplied integration servlet to your web.xml.

  <servlet>
    <servlet-name>Dispatcher</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>net.happygiraffe.jerseytest</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
 
  <servlet-mapping>
    <servlet-name>Dispatcher</servlet-name>
    <url-pattern>/*</url-pattern>
  </servlet-mapping>

I specified an extra parameter to say which package I want scanned for resources. Otherwise Jersey will scan everything in /WEB-INF/classes and /WEB-INF/lib by default. Anyway, this works a treat:

% curl -i http://localhost:8080/jerseytest/hello
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Content-Type: text/plain
Transfer-Encoding: chunked
Date: Sat, 13 Sep 2008 20:44:41 GMT

hello world

I’m going to play with this some more. The API feels quite nice. Particularly when compared to Restlets, which I found a little bit too uniform. Mind you, the latest restlet code has its own version of JSR 311 support, so it may still be useful. It’s also actually worth checking out the JSR-311 spec, as it’s quite readable.

One thought on “REST Web Services in Java

Comments are closed.