Friday, April 30, 2010

JAX-RS and Jersey

To start with let me give you an one line overview of Jersey, Jersey is the open source and JAX-RS (JSR 311) Reference Implementation for building RESTful Web services.

JAX-RS came along initially as a way of writing RESTful services on the Java platform; using annotations and loose coupling to bind resource beans and their public methods to URIs, HTTP methods and MIME content type negotiation. I've said before I think its awesome, one of the most impressive JSRs we've had.

Root Resource:

Here's simple POJOs (Plain Old Java Objects) that are annotated with @Path have at least one method annotated with @Path or a resource method designator annotation such as @GET, @PUT, @POST, or @DELETE. Resource methods are methods of a resource class annotated with a resource method designator.

The following code example of a root resource class using JAX-RS annotations Java Objects to create RESTful Web Services. The example code shown here is from one of the samples that ships with Jersey, the zip file of which can be found in the maven repository here.



// The Java class will be hosted at the URI path "/helloworld"
public class HelloWorldResource {
// The Java method will process HTTP GET requests
// The Java method will produce content identified by the MIME Media
// type "text/plain"
public String getClichedMessage() {
// Return some cliched textual content
return "Hello World";

Relative URI: @Path

The @Path annotation's value is a relative URI path. In the example above, the Java class will be hosted at the URI path /helloworld. This is an extremely simple use of the @Path annotation. What makes JAX-RS so useful is that you can embed variables in the URIs.

URI path templates are URIs with variables embedded within the URI syntax. These variables are substituted at runtime in order for a resource to respond to a request based on the substituted URI. Variables are denoted by curly braces. For example, look at the following @Path annotation:

Here a user will be prompted to enter their name, and then a Jersey web service configured to respond to requests to this URI path template will respond. For example, if the user entered their username as "Vikas", the web service will respond to the following URL:

Better Content Negotiation Support : @producer & @Consumes

The @Produces annotation is used to specify the MIME media types of representations a resource can produce and send back to the client. In this example, the Java method will produce representations identified by the MIME media type "text/plain".
you might want to prefer to return HTML over XML/JSON so unless folks ask specifically just for XML or JSON you return HTML.

Http Methods: @GET, @PUT, @POST, @DELETE and @HEAD

These are resource method designator annotations defined by JAX-RS and which correspond to the similarly named HTTP methods.

No comments:

Post a Comment