Saturday, 25 April 2015

AJAX : Reading JSON data from servlet


In this post, I am going to explain how to read JSON data from servlet using AJAX.

Following example read simple json data (List of states in India) from server and updates the jsp page accordingly.

In brief summary,
1. I am going to use gson package, to convert list of strings (state names) into json and send the converted json string as AJAX call response.

List<String> data = new ArrayList<String> ();

//Add some data to list
                 
Gson gson = new Gson();
String json = gson.toJson(data);

response.getWriter().write(json);

2.Once client receives json data, following function process json data and updates jsp page.

var myArr = JSON.parse(xmlhttp.responseText);
processList(myArr);
                                   
function processList(arr) {
         var out = "";
         var i;
         for (i = 0; i < arr.length; i++) {
                  out += arr[i] + "<br />"
         }
document.getElementById("myDiv").innerHTML = out;
}

Follow the procedure to develop complete application in Eclipse.

Step 1:
Create new “Dynamic Web Project” name it as “ajax_tutorial”.



Select the check box “Generate web.xml deployment descriptor” and press Finish.

Step 2: Convert Dynamic web project as maven project and add maven dependency for gson package. “gson” package is used to convert java object to json.


Update pom.xml, by adding gson dependency.

Final pom.xml looks like below.
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>ajax_tutorial</groupId>
  <artifactId>ajax_tutorial</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.1</version>
        <configuration>
          <source>1.6</source>
          <target>1.6</target>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-war-plugin</artifactId>
        <version>2.4</version>
        <configuration>
          <warSourceDirectory>WebContent</warSourceDirectory>
          <failOnMissingWebXml>false</failOnMissingWebXml>
        </configuration>
      </plugin>
    </plugins>
  </build>

  <dependencies>
    <dependency>
      <groupId>com.google.code.gson</groupId>
      <artifactId>gson</artifactId>
      <version>2.3.1</version>
    </dependency>

  </dependencies>
</project>

Step 3: Create Servlet IndiaStates.java.


import java.io.IOException;

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

import com.google.gson.Gson;

import java.util.*;

/**
 * Servlet implementation class IndiaStates
 */
@WebServlet("/IndiaStates")
public class IndiaStates extends HttpServlet {
  List<String> statesOfIndia = new ArrayList<String>();

  private List<String> getStatesOfIndia() {
    if (statesOfIndia.isEmpty()) {
      statesOfIndia.add("Andhra Pradesh");
      statesOfIndia.add("Arunachal Pradesh");
      statesOfIndia.add("Assam");
      statesOfIndia.add("Bihar");
      statesOfIndia.add("Chhattisgarh");
      statesOfIndia.add("Goa");
      statesOfIndia.add("Gujarat");
      statesOfIndia.add("Haryana");
      statesOfIndia.add("Himachal Pradesh");
      statesOfIndia.add("Jammu & Kashmir");
      statesOfIndia.add("Jharkhand");
      statesOfIndia.add("Karnataka");
      statesOfIndia.add("Kerala");
      statesOfIndia.add("Madhya Pradesh");
      statesOfIndia.add("Maharashtra");
      statesOfIndia.add("Manipur");
      statesOfIndia.add("Meghalaya");
      statesOfIndia.add("Mizoram");
      statesOfIndia.add("Nagaland");
      statesOfIndia.add("Odisha");
      statesOfIndia.add("Punjab");
      statesOfIndia.add("Rajasthan");
      statesOfIndia.add("Sikkim");
      statesOfIndia.add("Tamil Nadu");
      statesOfIndia.add("Telangana");
      statesOfIndia.add("Tripura");
      statesOfIndia.add("Uttarakhand");
      statesOfIndia.add("Uttar Pradesh");
      statesOfIndia.add("West Bengal");
    }
    return statesOfIndia;
  }

  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");

    List<String> data = getStatesOfIndia();

    Gson gson = new Gson();
    String json = gson.toJson(data);

    response.getWriter().write(json);
    response.getWriter().close();

  }

}


Step 4: Create index.jsp.
<!DOCTYPE html>
<html>
<head>
<script>
  function loadXMLDoc() {
    var xmlhttp;
    if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp = new XMLHttpRequest();
    } else {// code for IE6, IE5
      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function() {
      if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        //document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
        var myArr = JSON.parse(xmlhttp.responseText);
        processList(myArr);
      }
    }
    xmlhttp.open("POST", "/ajax_tutorial/IndiaStates", true);
    xmlhttp.setRequestHeader('Content-Type',
        'application/x-www-form-urlencoded');
    xmlhttp.send(null);
  }

  function processList(arr) {
    var out = "";
    var i;
    for (i = 0; i < arr.length; i++) {
      out += arr[i] + "<br />"
    }
    document.getElementById("myDiv").innerHTML = out;
  }
</script>
</head>
<body>

  <div id="myDiv">
    <h2>Click the button to change text</h2>
  </div>
  <button type="button" onclick="loadXMLDoc()">Change Content</button>

</body>
</html>
Final project structure looks like below.

Run the application “ajax_tutorial”.

Once you click on button “Change Content”, browser updates with all states of India.


Prevoius                                                 Next                                                 Home

No comments:

Post a Comment