In this article, we are going to discuss “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 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.
Sample Jersey REST Service com.sun.jersey.spi.container.servlet.ServletContainer com.sun.jersey.config.property.packages org.smarttechies.services 1 Jersey REST Service /*
As part of the 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 getProducts() { List products = new ArrayList(); Product product1 = new Product(); product1.setProdName("Giordano Analog Watch - For Men (Silver)"); product1.setProdPrice(1699); product1.setProdDesc("No description available"); product1.setActive(true); Map features1 = new HashMap(); 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 features2 = new HashMap(); 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 features = new HashMap(); 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 to the above request is given below.
true Type Analog Dial Color Black Strap Material Metal Strap No description available Giordano Analog Watch - For Men (Silver) 1699.0
Now, we will send a request to get the list of products. The request is http://localhost:8080/SampleREST/products
The response is given below.
true Type Analog Dial Color Black Strap Material Metal Strap No description available Giordano Analog Watch - For Men (Silver) 1699.0 true Lens Type NIKKOR Lens USB Cable Hi-speed USB Battery Type AA Alkaline Battery 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 Nikon Coolpix L28 Point & Shoot (Black) 5772.0
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.
Good article