Wednesday, May 14, 2014

Java JSON JQuery

This post is a small example web application using Java, JSON, JQuery.

JSON (JavaScript Object Notation) is now conquering the attention in the Web Applications, Mobile Applications, Big Data etc., If you don't know about JSON, properly it is about time to learn.

Example JSON:  {"name":"Book Name","author":"Book Author","publisher":"Book Publisher"}

We will be using the above JSON data in our example, it is basically key value pair. Both key value are enclosed in double quotes ".  "Key" : "Value"  separated by colon :

Subsequent key values are separated by comma , and complete data is enclosed in braces { }

Prerequisite Knowledge / Skills 
-- Java 
-- Eclipse IDE
-- Basic Javascript
-- Basic JQuery knowledge 

Development Tools Required
-- Eclipse IDE Juno / Kepler 
-- Tomcat 6.0 +

Design Concept 
BookServlet  --> Get Method will retrieve the List (ArrayList) of books  in JSON Format
BookServelt --> Post Method will add Book to the List(ArrayList)
index.jsp --> will place 2 types of request, one using get and another using post. Both request are sent to BookServlet but for different methods. 

Project Structure in Eclipse with Files 
JavaJQueryJson
--.settings
--build
--src
----com
------demo
--------json
----------Book.java (src / com / demo / json )
----------BookList.java (src / com / demo / json )
----------BookServlet.java (src / com / demo / json )
----------Status.java (src / com / demo / json )
--WebContent 
------index.jsp (WebContent )
------js
------------jquery-1.11.1.js (WebContent / js )
------META-INF
------WEB-INF
------------web.xml (WebContent / WEB-INF )
------------classes
------------lib
----------------gson-2.2.4.jar (WebContent / WEB-INF / lib )


Step 1: In your eclipse IDE create a dynamic web project


Step 2: Project name  JavaJQueryJson 

Step 3: We will  be using GSON framework Java Library

Open the URL --> Navigate to Downloads 
Step 4: Copy the jar file to the Web Project/WEB-INF/lib folder

Step 5: Create a new class


Step 6: Package name --> com.demo.json  & Name: Book


Step 7: Book.java is a POJO class with 3 attributes and getter & setter


package com.demo.json;

public class Book {
private String name;
private String author;
private String publisher;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}

}

Step 8: Create BookList Class



Step 9: BookList.java is a Singleton class to add list of Books and get list of Books



package com.demo.json;

import java.util.ArrayList;
import java.util.List;

public class BookList extends Status{
private static BookList bookListInstance = null;
private List<Book> bookList = new ArrayList<Book>();
private BookList()
{
}
public void addBook(Book book)
{
bookList.add(book);
}
public List<Book> getBooks()
{
return bookList;
}
public static BookList getInstance()
{
if(bookListInstance==null)
{
return new BookList();
}
else
{
return bookListInstance;
}
}

}

Step 10: Create new java class Status



Step 11: Status.java is a simple POJO class with getter and setter



package com.demo.json;

public class Status {
private boolean status;
private String description;
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}

}

Step12: Download JQuery from http://jquery.com/

And copy the js to the folder WebContent/js



Step 13:  Create a new Java Servlet 



Step 14: Name the Servlet as BookServlet


Step 15: doGet method implementation


Step 16: doPost method implementation




Source Code:

package com.demo.json;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

/**
 * Servlet implementation class BookServlet
 */
public class BookServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

private static BookList bkList = BookList.getInstance();

/**
* @see HttpServlet#HttpServlet()
*/
public BookServlet() {
super();
}

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
*      response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {

response.setContentType("application/json");

Gson gson = new Gson();

try {

System.out.println("BK List: " + gson.toJson(bkList.getBooks()));

response.getOutputStream().print(gson.toJson(bkList.getBooks()));
response.getOutputStream().flush();

System.out.println("doGet Success");

} catch (Exception ex) {
ex.printStackTrace();
Status status = new Status();
status.setStatus(false);
status.setDescription(ex.getMessage());
response.getOutputStream().print(gson.toJson(status));
response.getOutputStream().flush();
}
}

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
*      response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub

response.setContentType("application/json");

Gson gson = new Gson();

try {
StringBuilder sb = new StringBuilder();
String s;
while ((s = request.getReader().readLine()) != null) {
sb.append(s);
}

System.out.println("JSON Data: " + sb.toString());

Book book = (Book) gson.fromJson(sb.toString(), Book.class);

Status status = new Status();
if (book.getName() != null && !book.getName().trim().equals("")) {
status.setStatus(true);
status.setDescription("success");

bkList.addBook(book);
} else {
status.setStatus(false);
status.setDescription("Book name is null or empty");
}
response.getOutputStream().print(gson.toJson(status));
response.getOutputStream().flush();

System.out.println("doPost Success");

} catch (Exception ex) {
ex.printStackTrace();
Status status = new Status();
status.setStatus(false);
status.setDescription(ex.getMessage());
response.getOutputStream().print(gson.toJson(status));
response.getOutputStream().flush();
}
}

}


Step 17: index.jsp in the WebContent Folder


<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Java JQuery JSON </title>
<script src="./js/jquery-1.11.1.js"> </script>
<script>
$(document).ready(function(){
  $("button").click(function(){
   $.getJSON('http://localhost:8080/JavaJQueryJson/BookServlet', '' , function(result){
     $.each(result, function(i, field){
        $.each(field, function(key, value){ 
        $("#results").append(key +": "+ value + " &nbsp;&nbsp;&nbsp;&nbsp;");
        });
        $("#results").append(" <br/> ");      
     });
   });
  });
});
function isEmpty(val){
    return (val === undefined || val == null || val.length <= 0) ? true : false;
}
function addBooks()
{
if(isEmpty($('#bookname').val()))
{
alert("Book name cannot be null");
}else
{
var dataJson = '{"name" : "'+ $('#bookname').val()+'","author" : "'+ $('#bookname').val()+'","publisher": "'+ $('#bookname').val()+'"}';
   $.ajax({
       type: 'POST',
       url: 'http://localhost:8080/JavaJQueryJson/BookServlet',
       data: dataJson, // or JSON.stringify ({name: 'bookname'}),
       success: function(result) {  
       $.each(result, function(i, field){
           $("#status").append(i +": "+ field + " <br/> ");
       });
       },
       contentType: "application/json",
       dataType: 'json'
   });
}  
}
</script>
</head>
<body>
<input type="text" name="bookname" id="bookname" /> 
<input type="button" name="btnAdd" id="btnAdd" value="Add Books" onclick="addBooks()" />
<br></br>
<div id="status"></div>
<br></br>
<button>Get Books</button>
<div id="results"></div>
</body>
</html>

Step 18: Final Result