The road less taken

« Social Software for... | Main | Content negotiation... »
Friday Feb 08, 2008

An introduction to Jersey

What is jersey?

Jersey is not an island off the north coast of Normandy, France. Nor is it (despite the logo) a soft, plain-knitted fabric used for clothing cyclists.

Jersey is the open source (under the CDDL license) JAX-RS (JSR 311) Reference Implementation for building RESTful Web services.

Let's examine a simple Resource class in Jersey.

 1    // The Java class will be hosted at the URI path "/helloworld"
 2    @UriTemplate("/helloworld")
 3    public class HelloWorldResource {
 4    
 5        @HttpContext
 6        private UriInfo context;
 7
 8        /** Creates a new instance of HelloWorldResource */
 9        public HelloWorldResource() {
10        }
11
12       /**
13       * Retrieves representation of an instance of hello.world.HelloWorldResource
14       * @return an instance of java.lang.String
15       */
16       @HttpMethod("GET")
17       @ProduceMime("text/plain")
18       public String getClichedMessage() {
19       //Return some cliched textual content
20       "Hello World! Here is " + context.getAbsolutePath();
21       }
22    }

The HelloWorldResource class is a very simple Web resource. The URI path of the resource is "/helloworld" (line 2), it supports the HTTP GET method (line 16) and produces cliched textual content (line 20) of the MIME media type "text/plain" (line 17).

Java annotations are used to declare the URI path (line 2), the HTTP method (line 16) and the MIME media type (line 17).

Also note the @HttpContext annotation (line 5), which acts as a marker to say "Please inject an instance of the Java type, in this case UriInfo, after the class has been constructed." This use of annotations is a key feature of JSR 311.

Comments:

Post a Comment:
  • HTML Syntax: NOT allowed