Tuesday, January 05, 2010

RESTful service with JAX-RS is so easy, a caveman could do it

A recent project requires me to build a RESTful service that supports supports stream input, output and JAXB binding. After a quick research, I was amazed when I found how easy it is to build RESTful service using JAX-WS(JSR-311) and Apache CXF. Cut the chase, let the code talk.
import javax.xml.ws.rs.*;
@Path( "/hello" )
public interface Greeter {
@Path( "/{user}")
@Produces( "text/plain" )
public String sayHelloTo( @PathParam( "user" )String userName );
It seems the annotations in the interface above provides everything client needs to know, and that's exactly right. Following CXF class returns an implementation of Greeter that knows to send HTTP request to http://helloworld.com/hello/jiaqi and return the HTML response as a String. There's zero coding work involved to create fully functional client.
import org.apache.cxf.jaxrs.client.JAXRSClientFactory;
Greeter greeter = JAXRSClientFactory.create( "http://helloworld.com",
Greeter.class );
String result = greeter.sayHelloTo( "jiaqi" );
The server side code is even more amazing. Once interface is implemented, CXF provides library that seamlessly integrates arbitrary implementation with Servlet using Springframework. All you need to do is:

  • Making sure cxf-rt-frontend-jaxrs jar file and dependencies are in classpath. Which is simple in Maven:


  • CXF servlet and spring context listener is in web.xml

  • And tell Servlet to call my implementation in spring configuration

<beans xmlns:jaxrs="http://cxf.apache.org/jaxrs" ... >
<import resource="classpath:META-INF/cxf/cxf.xml" />
<import resource="classpath:META-INF/cxf/cxf-extension-jaxrs-binding.xml" />
<import resource="classpath:META-INF/cxf/cxf-servlet.xml" />
<jaxrs:server id="restfulService" address="/">
<ref bean="greeter" />
<bean name="greeter"
class="sample.GreeterImpl" ... >
CXF project has a document with super detailed examples, which talked about more flexible use cases such as arbitrary MIME type, HTTP headers, cookies and stream based API. RESTful Java with JAX-RS is a book that worth reading for JAX-RS loving people. Anyway, now it's time for me to rewrite all my services.

A caveman could do it