May 31, 2011

Ajax with JSON response and Java JSON library on server-side

0) Add the org.json.jar file to the WebContent/lib folder of the web application - download the jar file from here

1) Create a JSP - getOrderInfoJson.jsp - within the WebContent folder of your web application. The JSP contains the Javascript code to retrieve the response payload in JSON format and convert it into a Javascript object and extract the response data to modify the HTML DOM.

<html>
<head>
<title>Get Customer Orders - JSON Example</title>
<script type="text/javascript">

var request = null;
function createRequest() {

   try {
      request = new XMLHttpRequest();
   } catch (trymicrosoft) {
      try {
         request = new ActiveXObject("Msxml2.XMLHTTP");
      } catch (othermicrosoft) {
         try {
            request = new ActiveXObject("Microsoft.XMLHTTP");
         } catch (failed) {
            request = null;
         }
      }
   }
   if (request == null) {  
      alert("Error creating request object");   
   }
}

function checkOrder() {
   createRequest();
   request.open("POST", "jsonServlet", true);
   request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
   request.onreadystatechange = updatePage;
   request.send("customerId="+document.forms[0].elements[0].value);
}

var updatePage = function() {
   if (request.readyState == 4) {
      if (request.status == 200) {
         alert(request.responseText);
         var jsonCustomerObject = eval( "(" + request.responseText + ")");
    
         var toDisplay;
    
         toDisplay = "<span style='font-weight:bold;'> Customer Name:</span> " 
                  + jsonCustomerObject.realname + "<br/><br/>";

         toDisplay = toDisplay 
                  + "<span style='font-weight:bold;'>Order ID:</span> " 
                  + jsonCustomerObject.orders[0].id + "<br/>";
    
         toDisplay = toDisplay 
                  + "<span style='font-weight:bold;'>Date of Order:</span> " 
                  + jsonCustomerObject.orders[0].date + "<br/>";
    
         toDisplay = toDisplay 
                  + "<span style='font-weight:bold;'>Total Order Cost:</span> "  
                  + jsonCustomerObject.orders[0].cost + "<br/><br/>";
        
         toDisplay = toDisplay 
                  + "<span style='font-weight:bold;'>Details of Order</span> "  
                  + "<br/><br/>";
    
         for(var i=0; i<jsonCustomerObject.orders[0].items.length; i++) {

            toDisplay = toDisplay 
                  + "<span style='font-weight:bold;'>Item Id:</span> " 
                  + jsonCustomerObject.orders[0].items[i].id + "<br/>";
   
            toDisplay = toDisplay 
                  + "<span style='font-weight:bold;'>Item Name:</span> " 
                  + jsonCustomerObject.orders[0].items[i].name + "<br/>";
   
            toDisplay = toDisplay 
                  + "<span style='font-weight:bold;'>Item Price:</span> " 
                  + jsonCustomerObject.orders[0].items[i].price + "<br/>";
   
            toDisplay = toDisplay 
                  + "<span style='font-weight:bold;'>Item Description:</span> " 
                  + jsonCustomerObject.orders[0].items[i].description 
                  + "<br/>";
   
            toDisplay = toDisplay + "<br/><br/>";
         }
        
         document.getElementById('message').innerHTML = toDisplay;
      }
   }
}
</script>
</head>
<body>
<h1>Check Customer Order Information</h1>

<form>
   <label>Customer Id</label>: <input type="text" name="customerId" />
   <br/><br/>
   <input type="button" value="Submit" onclick="javascript:checkOrder();"/>
</form>
<br/>

<div id="message"></div>

</body>
</html>


2) Create a servlet - JsonServlet.java - within the src folder of the web application

import java.io.*;
import java.util.*;
import javax.servlet.http.*;
import org.json.*;

public class JsonServlet extends HttpServlet {
   public void doPost (HttpServletRequest req, HttpServletResponse res) 
      throws IOException {
      String custId = req.getParameter("customerId");
      Customer customer = getCustomer(custId);

      PrintWriter out = res.getWriter();
      res.setContentType("application/x-json");
      try {
         out.print(customer.toJSONObject());
         System.out.println(customer.toJSONObject());
      } catch (JSONException e) {
         e.printStackTrace();
      }
   }
   private Customer getCustomer(String id) {
      Item i1 = new Item();
      i1.setId("i-55768");
      i1.setDescription("512 Megabyte Type 1 CompactFlash card. Manufactured by Oolong Industries");
      i1.setName("Oolong 512MB CF Card");
      i1.setPrice(49.99);
      Item i2 = new Item();
      i2.setId("i-74491");
      i2.setDescription("7.2 Megapixel digital camera featuring six shooting modes and 3x optical zoom. Silver.");
      i2.setName("Fujak Superpix72 Camera");
      i2.setPrice(299.99);
      Item[] items = new Item[2];
      items[0] = i1;
      items[1] = i2;
      Order o1 = new Order();
      o1.setId("o-11123");
      o1.setCost(348.98);
      o1.setDate( new Date());
      o1.setItems(items);
      Order[] orders = new Order[1];
      orders[0] = o1;
      Customer c = new Customer();
      c.setRealname("Dinesh PC");
      c.setUsername("dinipc");
      c.setOrders(orders);

      return c;
   }
}

3) Configure the servlet in the web.xml file present within the WebContent/WEB-INF folder

<servlet>
    <servlet-name>jsonServlet</servlet-name>
    <servlet-class>JsonServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>jsonServlet</servlet-name>
    <url-pattern>/jsonServlet</url-pattern>
</servlet-mapping>


4) Add the classes - Customer.java,  Order.java and Item.java - within the src folder of the web application. These classes contain the toJSONObject() methods that use the org.json API methods to serialize the output response into the JSON format

import java.util.*;
import org.json.*;

public class Customer {
   private String username; 
   private String realname;
   private Order[] orders;
   public String getUsername() {
      return username;
   }
   public void setUsername(String username) {
      this.username = username;
   }

   public String getRealname() {
      return realname;
   }
   public void setRealname(String realname) {
      this.realname = realname;
   }

   public Order[] getOrders() {
      return orders;
   }

   public void setOrders(Order[] orders) {
      this.orders = orders;
   }

   public JSONObject toJSONObject() throws JSONException {

      JSONObject json = new JSONObject();
      json.put("realname", realname);
      json.put("username", username);
 
      JSONArray jsonItems = new JSONArray();
 
      for (int i=0; i<orders.length; i++ ) {
         jsonItems.put(orders[i].toJSONObject());
      }
 
      json.put("orders",jsonItems);

      return json;
   }

}


import java.util.*;
import org.json.*;

public class Order {
   private String id;
   private Date date;
   private double cost;
   private Item[] items;
   public String getId() {
      return id;
   }
   public void setId(String id) {
      this.id = id;
   }
   public Date getDate() {
      return date;
   }
   public void setDate(Date date) {
      this.date = date;
   }
   public double getCost() {
      return cost;
   }
   public void setCost(double cost) {
      this.cost = cost;
   }
   public Item[] getItems() {
      return items;
   }
   public void setItems(Item[] items) {
      this.items = items;
   }
   public JSONObject toJSONObject() throws JSONException {

      JSONObject json = new JSONObject();
      json.put("id", id);
      json.put("cost", cost);
      json.put("date", date.toString());

      JSONArray jsonItems = new JSONArray();
 
      for (int i=0; i<items.length; i++ ) {
         jsonItems.put(items[i].toJSONObject());
      }
      json.put("items",jsonItems);

      return json;
   }
}


import java.util.Iterator;
import org.json.*;

public class Item {
   private String id;
   private String name;
   private String description;
   private double price;
   public String getId() {
      return id;
   }
   public void setId(String id) {
      this.id = id;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
   public String getDescription() {
      return description;
   }
   public void setDescription(String description) {
      this.description = description;
   } 
   public double getPrice() {
      return price;
   }
   public void setPrice(double price) {
      this.price = price;
   }

public JSONObject toJSONObject() throws JSONException {

JSONObject json = new JSONObject();
json.put("id", id);
json.put("name", name);
json.put("description", description);
json.put("price", price);

return json;
}

}

5) Test the example with the following URL in the browser:

http://localhost:8080/WebAppName/jsonServlet

No comments:

Post a Comment