Srikanth Technologies

How to use Jersey + Jackson + jQuery

In this blog, I discuss about the following: Note : Read my blog on CRUD Operations with Restful Service to know how to use Create, Read, Update and Delete operations with Restful Service.

Creating Restful Web Service with Jersey

Here are the steps to create a RESTFul web service that supports Http GET method.
  1. Start Eclipse Mars (Even older versions will do).
  2. Create a new Dynamic Web Project called catalog.
  3. We need an implementation of jax-rs. We use Jersey. Download Jersey 2.23.1 by going to their website https://jersey.java.net/download.html and clicking on Jersey JAX-RS 2.0 RI Bundle.
  4. When jaxrs-ri-2.23.1.zip is downloaded, extract it into a folder like d:\java\jaxrs-ri-2.23.1.
  5. Get into that folder and copy all .jar files from lib, ext and api folders into WEB-INF/lib folder of our project in Eclipse.
  6. Create the following Java classes that are used in Restful service.

    Book.java

    Book class represents a book. It contains id, title and price properties.
    package rest;
    import javax.xml.bind.annotation.XmlRootElement;
    public class Book {
    	private int id;
    	private String title;
    	private double price;
    	public Book() {
    	}
    	public Book(int id, String title, double price) {
    		super();
    		this.id = id;
    		this.title = title;
    		this.price = price;
    	}
    	public int getId() {
    		return id;
    	}
    	public void setId(int id) {
    		this.id = id;
    	}
    	public String getTitle() {
    		return title;
    	}
    	public void setTitle(String title) {
    		this.title = title;
    	}
    	public double getPrice() {
    		return price;
    	}
    	public void setPrice(double price) {
    		this.price = price;
    	}
    }
    

    Books.java

    Books class creates a set of Book objects. To keep it simple, I am creating a few objects and putting them in an ArrayList.
    package rest;
    import java.util.ArrayList;
    import java.util.List;
    
    public class Books {
    	private static ArrayList<Book> books = new ArrayList<>();
    	static {
    		books.add(new Book(1, "The Outliers", 500));
    		books.add(new Book(2, "World Is Flat", 550));
    	}
    	public static List<Book> getBooks() {
    		return books;
    	}
    }
    
  7. Now, create BookService.java, which is a Restful service with the following characteristics.
    • It supports URLs /books and /books/id
    • It throws NotFoundException when the given book id is not found
    • Method getBooks() returns a List of Book objects and getBook() returns a single Book object based on the given id
    • As this project uses Jackson, it will convert these Java objects to JSON before sending data to client

    BookService.java

    package rest;
    import java.util.List;
    import javax.ws.rs.GET;
    import javax.ws.rs.NotFoundException;
    import javax.ws.rs.Path;
    import javax.ws.rs.PathParam;
    import javax.ws.rs.Produces;
    import javax.ws.rs.core.MediaType;
    
    @Path("/books")
    public class BookService {
    	List<Book> books;
    	public BookService() {
    		books = Books.getBooks();
    	}
    	@GET
    	@Produces(MediaType.APPLICATION_JSON)
    	public List<Book> getBooks() {
    		return books;
    	}
    	@Path("{id}")
    	@GET
    	@Produces(MediaType.APPLICATION_JSON)
    	public Book getBook(@PathParam("id") int id) {
    		  for(Book b : books) {
    			  if ( b.getId() == id)
    				   return b;
    		  }
    		  // book with the given id is not found, so throw 404 error
    		  throw new NotFoundException(); 
    	}
    }
    
  8. To use Jersey, we need to add Jersey servlet configuration to web.xml. So lets first create web.xml
    • Select project (catalog) and right click to get popup menu
    • Select Java EE Tools -> Generate Deployment Descriptor Stub. It will create WEB-INF/web.xml
    • Add the following servlet configuration to web.xml as follows:

      <?xml version="1.0" encoding="UTF-8"?>
      <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      	xmlns="http://xmlns.jcp.org/xml/ns/javaee"
      	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
      	version="3.1">
      	<display-name>catalog</display-name>
      	<servlet>
      		<servlet-name>Jersey REST Service</servlet-name>
      		<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
      
      		<init-param>
      			<param-name>jersey.config.server.provider.packages</param-name>
      			<param-value>rest</param-value>
      		</init-param>
      		<load-on-startup>1</load-on-startup>
      	</servlet>
      	<servlet-mapping>
      		<servlet-name>Jersey REST Service</servlet-name>
      		<url-pattern>/rest/*</url-pattern>
      	</servlet-mapping>
      </web-app>
      
  9. Now our Restful Service is ready to be accessed from client. But it still cannot convert Java objects to JSON. To convert Book object to JSON we need to add Jackson libraries to our project.

Adding Jackson to Project

In order to convert Java objects to JSON, we need to use Jackson library in this project.

To use Jackson, we need to download a set of .jar files related to Jackson and place them in WEB-INF/lib folder.

Here is the list of .jar files and URLs from where you can download them. Download all these .jars and place them in WEB-INF/lib folder.

Following screenshot shows WEB-INF/lib folder after all .jars related to Jersey and Jackson are placed.

Testing Service

It is time to test our service.

Start Tomcat and add catalog project to it.

In my system Tomcat runs at port no. 8888. So change port numbers in the url according to your Tomcat port no. Also remember rest in url is url pattern associated with jersey container as shown in web.xml.

The following screenshots show what happens when you give /books and /books/1 urls. Full URL is  http://localhost:8888/catalog/rest/books

Creating Client using jQuery

The following HTML page uses jQuery to make Ajax request to Restful service. We can either ask for one book by its id or get list of all books.

Make sure you download jquery from jquery.com and place .js file in Web Content folder.

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Books</title>
<script type="text/javascript" src="jquery-3.1.0.js">
</script>
<script>
  function getDetails() {
	     // getJSON returns Promise object, which contains done(), always() and fail() methods
	     // use fail() to respond to failed request like 404
	     var promise = $.getJSON("http://localhost:8888/catalog/rest/books/" + $("#id").val(),{}, showBook);
	     promise.fail(showError);   // getJSON returns promise object.
  }
  function showBook(book)
  {
	  $("#title").text(book.title);
	  $("#price").text(book.price);
  }
  
  function showError()
  {
	  $("#title").text("Sorry! Book not found!");
	  $("#price").text("");
  }
</script>
</head>
<body>
	<h2>Books Client</h2>
 	Book Id : <br/>
	<input type="text" id="id" /> 
	<button onclick="getDetails()">Details </button>
	<p />
        <div id="title"></div>
	<p />
        <div id="price"></div>
</body>
</html>


Post Your Comment

Image

Enter the code given in the above image :
Enter Your Name :
Enter Your Email Address :
Enter Your Comment :

Comments