How to create RESTful web services using jersy

               Smart Techie

               In this article, we are going to discuss about “how to create REST(Representational State Transfer) service?” using Jersy implementation. Jersey is the open source, production quality, JAX-RS (JSR 311) reference implementation for building RESTful Web services. You can download the zip of Jersy containing the Jersy jars, core dependencies.

After downloading of the Jersy jars, follow the below steps to create RESTful  service.

Step 1:  Set up the development environment

  • Create a web application project. In this case, we have created a web application called “SampleREST” using eclipse IDE.
  • Extract the downloaded zip folder and put the  asm-3.1.jar,jaxb-api-2.2.4.jar,jaxb-impl-2.2.4-1.jar,jersey-core-1.17.jar,jersey-json-1.17.jar,jersey-server-1.17.jar,jersey-servlet-1.17.jar,jettison-1.1.jar,jsr311-api-1.1.1.jar,stax-api-1.0-2.jar files in to the class path( Copy the jar files in to the lib folder).
  • Jboss-5.1.0.GA application server or Apache tomcat container

Step 2: Developing the REST service

Now the development environment is ready to develop the REST web service. To do this, we need to redirect all the requests to the Jersy container by defining the servlet dispatcher in web.xml as given below.


<servlet>
 <servlet-name>Sample Jersey REST Service</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>org.smarttechies.services</param-value>
 </init-param>
 <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
 <servlet-name>Jersey REST Service</servlet-name>
 <url-pattern>/*</url-pattern>
</servlet-mapping>

As part of init parameter, define the package name which has resources.

Step 3: Now, we will write a resource called “ProductDetailsService”. The code is given below.


package org.smarttechies.services;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.smarttechies.model.Product;

@Path("/")
public class ProductDetailsService {

 @GET
 @Path("/products")
 @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
 public List<Product> getProducts() {
 List<Product> products = new ArrayList<Product>();
 Product product1 = new Product();
 product1.setProdName("Giordano Analog Watch - For Men (Silver)");
 product1.setProdPrice(1699);
 product1.setProdDesc("No description available");
 product1.setActive(true);
 Map<String, String> features1 = new HashMap<String, String>();
 features1.put("Type", "Analog");
 features1.put("Strap Material", "Metal Strap");
 features1.put("Dial Color", "Black");
 product1.setFeatures(features1);

 Product product2 = new Product();
 product2.setProdName("Nikon Coolpix L28 Point & Shoot (Black)");
 product2.setProdPrice(5772);
 product2.setProdDesc("Compact Digital Camera, Lens Construction: 6 Elements in 5 Groups, Focus-area Selection Center, 5 Level Brightness Adjustment, Frame Coverage Shooting Mode: 98% Horizontal and 98% Vertical, Frame Coverage Playback Mode: 98% Horizontal and 98% Vertical, Continuous Shooting: Single, Continuous (Six Images are Captured Continuously at Rate of About 1.1 fps), BSS (Best Shot Selector), 16 Multi-shot, Exposure Metering Mode: Matrix, Center-weighted, Spot, Exposure Control: Programmed Auto Exposure, Exposure Compensation: -2.0 - +2.0 EV in increment of 1/3 EV, Shutter: Mechanical and Charge-coupled Electronic Shutter, 2 Steps Aperture Range, Flash Control: TTL Auto Flash with Monitor Preflashes, Data Transfer Protocol: MTP, PTP, Input / Output Terminal: Audio / Video (A/V) Output, Digital Input / Output (USB), 1/4 inch Tripod Socket, Temperature: 0 - 40° C, Humidity: 85%, One-touch 720p HD Movie Recording, Smart Portrait System, Motion Blur Reduction, Easy-to-hold Handgrip Design Stylish Body with High-grade Metallic Exterior, Color Variations for Aluminum Lens Ring and Lens Barrel, EXPEED C2 Image Processing System, Wireless Transfer, Frame the Perfect Shot, Motion Detection");
 product2.setActive(true);
 Map<String, String> features2 = new HashMap<String, String>();
 features2.put("Battery Type", "AA Alkaline Battery");
 features2.put("USB Cable", "Hi-speed USB");
 features2.put("Lens Type", "NIKKOR Lens");
 product2.setFeatures(features2);

 products.add(product1);
 products.add(product2);
 return products;
 }

 @GET
 @Path("/product/{id}")
 @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
 public Product getProduct(@PathParam("id") String id) {
 Product product = new Product();
 product.setProdName("Giordano Analog Watch - For Men (Silver)");
 product.setProdPrice(1699);
 product.setProdDesc("No description available");
 product.setActive(true);
 Map<String, String> features = new HashMap<String, String>();
 features.put("Type", "Analog");
 features.put("Strap Material", "Metal Strap");
 features.put("Dial Color", "Black");
 product.setFeatures(features);
 return product;
 }
}

From the above code , we need to discuss some important points.

  • The “Resource” class is a simple java class. No need to implement any interfaces.
  • The annotations which we have used are part of JAX-RS.
  • @GET means, the following service responds to the HTTP GET request.
  • @Path defines the request path where the service will be available. For example http://localhost:8080/SampleREST/products
  • @Produces defines the MIME type of the response.

Step 4: Test the REST service

In the service, we have defined REST services to get the product based on product id and the list of the products.

First, we will send the request to get the product info based on id. The request is http://localhost:8080/SampleREST/product/1

The response for the above request is given below.


<product>
<active>true</active>
<features>
<entry>
<key>Type</key>
<value>Analog</value>
</entry>
<entry>
<key>Dial Color</key>
<value>Black</value>
</entry>
<entry>
<key>Strap Material</key>
<value>Metal Strap</value>
</entry>
</features>
<prodDesc>No description available</prodDesc>
<prodName>Giordano Analog Watch - For Men (Silver)</prodName>
<prodPrice>1699.0</prodPrice>
</product>

Now, we will send request to get the list of products. The request is http://localhost:8080/SampleREST/products

The response is given below.


<products>
<product>
<active>true</active>
<features>
<entry>
<key>Type</key>
<value>Analog</value>
</entry>
<entry>
<key>Dial Color</key>
<value>Black</value>
</entry>
<entry>
<key>Strap Material</key>
<value>Metal Strap</value>
</entry>
</features>
<prodDesc>No description available</prodDesc>
<prodName>Giordano Analog Watch - For Men (Silver)</prodName>
<prodPrice>1699.0</prodPrice>
</product>
<product>
<active>true</active>
<features>
<entry>
<key>Lens Type</key>
<value>NIKKOR Lens</value>
</entry>
<entry>
<key>USB Cable</key>
<value>Hi-speed USB</value>
</entry>
<entry>
<key>Battery Type</key>
<value>AA Alkaline Battery</value>
</entry>
</features>
<prodDesc>
Compact Digital Camera, Lens Construction: 6 Elements in 5 Groups, Focus-area Selection Center, 5 Level Brightness Adjustment, Frame Coverage Shooting Mode: 98% Horizontal and 98% Vertical, Frame Coverage Playback Mode: 98% Horizontal and 98% Vertical, Continuous Shooting: Single, Continuous (Six Images are Captured Continuously at Rate of About 1.1 fps), BSS (Best Shot Selector), 16 Multi-shot, Exposure Metering Mode: Matrix, Center-weighted, Spot, Exposure Control: Programmed Auto Exposure, Exposure Compensation: -2.0 - +2.0 EV in increment of 1/3 EV, Shutter: Mechanical and Charge-coupled Electronic Shutter, 2 Steps Aperture Range, Flash Control: TTL Auto Flash with Monitor Preflashes, Data Transfer Protocol: MTP, PTP, Input / Output Terminal: Audio / Video (A/V) Output, Digital Input / Output (USB), 1/4 inch Tripod Socket, Temperature: 0 - 40° C, Humidity: 85%, One-touch 720p HD Movie Recording, Smart Portrait System, Motion Blur Reduction, Easy-to-hold Handgrip Design Stylish Body with High-grade Metallic Exterior, Color Variations for Aluminum Lens Ring and Lens Barrel, EXPEED C2 Image Processing System, Wireless Transfer, Frame the Perfect Shot, Motion Detection
</prodDesc>
<prodName>Nikon Coolpix L28 Point & Shoot (Black)</prodName>
<prodPrice>5772.0</prodPrice>
</product>
</products>

We have seen the response in XML format. If you want the response in JSON format, we need to send the request with “Accept” header “application/json”. Then,  the response  will be in JSON format.

{"product":[{"active":"true","features":{"entry":[{"key":"Type","value":"Analog"},{"key":"Dial Color","value":"Black"},{"key":"Strap Material","value":"Metal Strap"}]},"prodDesc":"No description available","prodName":"Giordano Analog Watch - For Men (Silver)","prodPrice":"1699.0"},{"active":"true","features":{"entry":[{"key":"Lens Type","value":"NIKKOR Lens"},{"key":"USB Cable","value":"Hi-speed USB"},{"key":"Battery Type","value":"AA Alkaline Battery"}]},"prodDesc":"Compact Digital Camera, Lens Construction: 6 Elements in 5 Groups, Focus-area Selection Center, 5 Level Brightness Adjustment, Frame Coverage Shooting Mode: 98% Horizontal and 98% Vertical, Frame Coverage Playback Mode: 98% Horizontal and 98% Vertical, Continuous Shooting: Single, Continuous (Six Images are Captured Continuously at Rate of About 1.1 fps), BSS (Best Shot Selector), 16 Multi-shot, Exposure Metering Mode: Matrix, Center-weighted, Spot, Exposure Control: Programmed Auto Exposure, Exposure Compensation: -2.0 - +2.0 EV in increment of 1/3 EV, Shutter: Mechanical and Charge-coupled Electronic Shutter, 2 Steps Aperture Range, Flash Control: TTL Auto Flash with Monitor Preflashes, Data Transfer Protocol: MTP, PTP, Input / Output Terminal: Audio / Video (A/V) Output, Digital Input / Output (USB), 1/4 inch Tripod Socket, Temperature: 0 - 40° C, Humidity: 85%, One-touch 720p HD Movie Recording, Smart Portrait System, Motion Blur Reduction, Easy-to-hold Handgrip Design Stylish Body with High-grade Metallic Exterior, Color Variations for Aluminum Lens Ring and Lens Barrel, EXPEED C2 Image Processing System, Wireless Transfer, Frame the Perfect Shot, Motion Detection","prodName":"Nikon Coolpix L28 Point & Shoot (Black)","prodPrice":"5772.0"}]}

The source code is available at https://github.com/2013techsmarts/SampleREST. We can integrate the Jersy with other frameworks like Spring, Guice and we can get the response in other formats like atom. In the coming session, we will see how we can develop RESTful services using Spring.

Advertisements

I am Siva Prasad Rao Janapati. Working as a software developer. Has hands on experience on ATG Commerce(DAS/DPS/DCS), Mozu commerce, Broadleaf Commerce, Java, JEE, Spring, Play, JPA, Hibernate, Velocity, JMS, Jboss, Weblogic,Tomcat, Jetty, Apache, Apache Solr, Spring Batch, JQuery, NodeJS, SOAP, REST, MySQL, Oracle, Mongo DB, Memcached, HazelCast, Git, SVN, CVS, Ant, Maven, Gradle, Amazon Web services, Rackspace, Quartz, JMeter, Junit, Open NLP, Facebook Graph,Twitter4J, YouTube Gdata, Bazzarvoice,Yotpo, 4-Tell, Alatest, Shopzilla, Linkshare. I have hands on experience on open sources and commercial technologies.

Tagged with: , ,
Posted in JAX-RS, Jersy REST, REST Services
One comment on “How to create RESTful web services using jersy
  1. Anonymous says:

    Good article

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

DZone

DZone MVB

Java Code Geeks
Java Code Geeks
%d bloggers like this: