Sunday, February 16, 2014

Creating a Simple Web Service with Jersey Framework



Hi , This is my first post on web service . Lets start with the basic concept of REST based architecture    Then we will jump into the jersey framework , a reference implementation of JAX-RS . So lets start :)

What are RESTful Web Services ?
REST stands for Representational State Transfer . Its a key idiom that embraces a stateless client-server architecture in which the web services are viewed as resources and can be identified by their URLs.  REST was first described by Roy Fielding in the year 2000.


RESTful webservices are based on the concept of REST and exposes a set of resources that are identified by URLs .

Wikipedia Says -
REST is an architectural style consisting of a coordinated set of constraints applied to components, connectors, and data elements, within a distributed hypermedia system. 

REST ignores the details of component implementation and protocol syntax in order to focus on the roles of components, the constraints upon their interaction with other components, and their interpretation of significant data elements .


HTTP Methods
GET , POST , PUT , DELETE are the common http methods that are used with the web services . 

Constraints
The REST architecture applies specific interaction constraints on components , connectors and data elements .  In order for an architecture to be a REST architecture, it must satisfy all of these constraints. 

1. Client–Server

The first constraint is the Client-Server constraint and it is based on the principle of separation of concern  . It states that the client and Server should have a uniform interface between them . This provides the flexibility to change them independently ( As long as the interface between them is not altered ).

2. Layered System
Similar to the client-server constraint, this constraint improves simplicity by separating concerns. A client and server may have multiple intermediary layers between them . This can be used to increase the scalability of the architecture as the intermediary layers can be used load balancing , or providing shared caches.

3. Stateless Communication
This constraint states that every request should contain all the information that is required to interpret that request.  This increases the visibility, reliability, scalability, but also decreases performance because of the larger messages required for stateless communication.

4. Caching Constraint
There must be a mechanism such that the Responses can define themselves as cacheable or non-cacheable . Well managed caching improves the scalability and performance .

5. Code on Demand
Code on demand is the only optional constraint of the REST architecture. This constraint extends the functionality of the client by transferring the executable code. Example Java applets.

6. Uniform Interface
The Uniform interface simplifies and decouples the architecture . The Uniform interface is fundamental to design of any REST based architecture.

6.a.  Identification of resources
Resources are identified using the URIs in a web-based REST architecture. 
Individual resources are identified in requests, for example using URIs in web-based REST systems. The resources themselves are conceptually separate from the representations that are returned to the client.

6.b.  Manipulation of resources through these representations
The representation of a resource (including any metadata ) has enough information and can be used by the client to modify the resource on the server.

6.c.  Self-descriptive messages
The messages must include metadata which describe the meaning of the message. The metadata helps in identifying how to process the message. 
Responses also explicitly indicate their cacheability. 

6.d.  Hypermedia Constraint

The steps in a REST architecture must be invoked through hypermedia.

Applications conforming to the above constraints can be considered as  RESTful.  If a service violates any of the required constraints , it cannot be considered RESTful . 



When should we use REST ?
A RESTful design may be appropriate when -
  • The web services are completely stateless . 
  • When bandwidth is important and is limited . REST is useful for limited profile devices such as mobiles and PDAs.
  • When caching mechanism can be leveraged for enhancing the performance .For example for the responses that are not dynamic can be cached to increase the performance.
  • SOAP based design is appropriate when a formal contract must be established to describe the interface that the web service offers. The WSDL ( Web Service Description Language ) describes the details such as messages , operations , bindings , and location of webservice.
  • When the architecture must address complex non-functional requirements . Example - Security , transactions  etc. With REST ful approach in such scenarios , developers must build this plumbing into the application layers themselves.
  • When the architecture needs to handle asynchronous processing and invocation . In such cases , the infrastructure provided by the standards such as WSRM and APIs such as JAX-WS with their client-side asynchronous invocation support can be leveraged out of the box.

JAX-RS
JAX-RS stands for Java API for RESTful Web Services . JAX-RS is an API that provides support for creating web services based on REST (Representational State Transfer) architectural pattern .  JAX-RS uses annotations ( Introduces in java SE 5 ) for the simplification of the development and deployment of web service clients and endpoints .


Important annotations in JAX-RS

JAX-RS provides a set of annotations in order to map a java class as a Resource.


@Path Denotes the relative path for a resource (class or method).
@GET, @PUT, @POST, @DELETE and @HEADHTTP request type.
@ProducesSpecifies the response media types.
@ConsumesSpecifies the accepted request media types .
@PathParamBinds the method parameter to a path segment.
@QueryParamBinds the method parameter to the value of an HTTP query parameter.
@MatrixParamBinds the method parameter to the value of an HTTP matrix parameter.
@HeaderParamBinds the method parameter to an HTTP header value.
@CookieParamBinds the method parameter to a cookie value.
@FormParamBinds the method parameter to a form value.
@DefaultValueSpecifies a default value for the above bindings when the key is not found.
@Context Returns the entire context of the object.(for example @Context HttpServletRequest request)


Implementations of JAX-RS
There are a lot of implementations of REST in the market . Some of them are -
Jersey is an open source framework for developing REST based web services in Java .
Jersey is a JAX-RS  ( JSR 311 & JSR 339 )  reference implementation . 

To download Jersey , Click here.
To know the list of dependencies , Click here.


Creating Sample application in Jersey 
So far , so good . Now we know the basics of REST . So lets create a sample application in Jersey. We will use Maven for dependency management . 

Step 1 - Creating maven project in Eclipse Juno
Step 2 - Adding dependencies in POM.
Step 3 - Creating a Service
Step 4 - Modifying the web.xml
Step 5 - Testing the application

Step 1 - Creating maven project in Eclipse Juno
The screenshots below shows how to create a maven project in eclipse .

a. Create a Maven project


Create a Maven project

b. Select Project name and location


Select Project name and location

c. Select an Archetype


Select an Archetype

d. Specify Archetype parameters. 


Specify Archetype parameters


Step 2 - Adding dependencies in POM.
We just need to declare jersey-server in pom .

 <project ...
 <repositories>
  <repository>
   <id>maven2-repository.java.net</id>
   <name>Java.net Repository for Maven</name>
   <url>http://download.java.net/maven/2/</url>
   <layout>default</layout>
  </repository>
 </repositories>

 <dependencies>
 <dependency>
  <groupId>com.sun.jersey</groupId>
  <artifactId>jersey-server</artifactId>
  <version>1.8</version>
 </dependency>

 </dependencies>
 </project>
 
Step 3 - Creating a Service


package com.javaworld;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;

@Path("/hello")
public class MyFirstService {
 @GET
 @Path("/{param}")
 public Response getMsg(@PathParam("param") String msg) {

  String output = "Hello : " + msg;

  return Response.status(200).entity(output).build();
 }
}



Step 4 - Modifying the web.xml
 
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"                                      
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
  <display-name>Restful Web Application</display-name>
 
  <servlet>
     <servlet-name>jersey-serlvet</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>com.javaworld</param-value>
     </init-param>
     <load-on-startup>1</load-on-startup>
  </servlet>
 
  <servlet-mapping>
  <servlet-name>jersey-serlvet</servlet-name>
  <url-pattern>/rest/*</url-pattern>
  </servlet-mapping>
 
</web-app>
 

Step 5 - Testing the application
Now just run the maven command mvn clean install on the project and it will create the war file in target folder . Simply copy the war to tomcat's webapps directory and start the server.

Now open a browser and type the following URL
http://localhost:8080/restExample/rest/hello/prakash

You will see a response as below -



Great !!! We are done with our first web service .

References
http://www.vogella.com/tutorials/REST/article.html
http://www.oracle.com/technetwork/articles/javase/index-137171.html
https://jersey.java.net/
http://www.oracle.com/technetwork/articles/javaee/jersey-part1-159891.html
http://wwatson.me/2011/10/13/rest-constraints-part-5/


8 comments :

  1. Your blog was well briefly explaining the process of create the simple website with jersey framework.This is really helpful for the web developers who are the beginning stage in jersey field.
    Web Designing Companies | Web Design Companies

    ReplyDelete
  2. A web development company can offer your business not only web development services but, also a range of other services which can take your company to the very top. However, most importantly, these companies can offer you with a team of highly skilled web designers who can design the very best page for your company.

    ReplyDelete
  3. Thanks for informative post which is very useful. I appreciate the blog author and like the articles of these blog.
    Web Development Company in Indore

    ReplyDelete
  4. Thanks for informative post which is very useful. I appreciate the blog author and like the articles of these blog.
    Web Development Company in Indore

    ReplyDelete
  5. The Java complies Source Coding into a format known as "Byte-Code". The Byte-code source files is then executed by interpreter. While using arrays, we create objects for arrays where class is non-existent. Whenever JVM encounters It understands that it must create an object. Thus, array object can be created without using the new operator. Find more Tips and JAVA Homework Help in Array.

    ReplyDelete
  6. Thanks for sharing this blog. It's very informative and very knowledgeable blog.

    ReplyDelete