Thursday, January 10, 2008

Getting Started with JAX-RS and Jersey - Simple REST Web Services for Java

I came across the need once again to build a public facing web services API and we all know that to be in the cool gang these days, you have to do it REST style. Now I've been a big fan of REST over SOAP (or any other type) for a long time for one simple reason: it's simpler. And simple is king in my books. Anyways, I decided to see if anyone had come up with a good, simple REST framework for java since there hasn't really been anything that I've found over the years.

With a little digging, I found what I had been looking for and it goes by the name JAX-RS (jsr311). Now this is pretty bleeding edge, the buzz has just started in the past few months and there's not much around to help you out. But as you should see in the samples below, it's well worth checking out.

Now lets get into the nitty gritty:

1. Download Jersey and add required jars to classpath

Jersey is the reference implementation, get it here.

Now you only need three jars from the Jersey download:

  • asm-3.X.jar
  • jersey.jar
  • jsr311-api.jar

That's all you need. Compare that to Axis and this alone should make you want to switch.

2. Add the Jersey Servlet to web.xml

You can use a lightweight http server that comes with the JDK or Jersey, but who's gonna do that in the real world? So here is how to get it running in Tomcat.

<servlet>
        <servlet-name>JerseyWebApplication</servlet-name>
        <servlet-class>com.sun.ws.rest.spi.container.servlet.ServletContainer</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>JerseyWebApplication</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>

3. Make a service bean

Now all you have to do is make service beans via JAX-RS annotations. This is remarkably easy. We'll start with the simplest Hello World example:

@Path("/helloworld") // sets the path for this service
public class HelloWorldBean {
@GET // This method will process GET
// requests to the @Path value set above
@ProduceMime("text/html") // content type to output
public String getClichedMessage() {
return "Hello World";
}
}


4. Run Tomcat and browse to /helloworld



Startup tomcat with your /WEB-INF/web.xml, the 3 jars in /WEB-INF/lib, and your compiled HelloWorldBean in /WEB-INF/classes. Now browse to http://localhost:8080/yourContext/rest/helloworld



You should see in your browser: Hello World.



That should give you all the basics you'll need to get started. Next time I'll post how to easily send XML responses directly from your objects.