Saturday, 25 April 2015

AJAX : Read Java map 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 (Map of states and capitals 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.

Map<String, String> data = getStatesOfIndia();

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 myMap = JSON.parse(xmlhttp.responseText);
processMap(myMap);
        
function processMap(myMap) {
    out = "<table border='1'>";
    
    for(data in myMap){
      
      out += "<tr><td>" + data + "</td><td>" + myMap[data] + "</td></tr>";
      //out += data + " " + myMap[data] + "<br />";
    }
    
    out += "</table>";
    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 {
  Map<String, String> statesOfIndia = new LinkedHashMap<String, String>();

  private Map<String, String> getStatesOfIndia() {
    if (statesOfIndia.isEmpty()) {
      statesOfIndia.put("Andhra Pradesh", "Hyderabad");
      statesOfIndia.put("Arunachal Pradesh", "Itanagar");
      statesOfIndia.put("Assam", "Dispur");
      statesOfIndia.put("Bihar", "Patna");
      statesOfIndia.put("Chhattisgarh", "Raipur");
      statesOfIndia.put("Goa", "Panaji");
      statesOfIndia.put("Gujarat", "Gandhinagar");
      statesOfIndia.put("Haryana", "Chandigarh");
      statesOfIndia.put("Himachal Pradesh", "Shimla");
      statesOfIndia.put("Jammu & Kashmir", "Srinagar & Jammu");
      statesOfIndia.put("Jharkhand", "Ranchi");
      statesOfIndia.put("Karnataka", "Bangalore");
      statesOfIndia.put("Kerala", "Thiruvananthapuram");
      statesOfIndia.put("Madhya Pradesh", "Bhopal");
      statesOfIndia.put("Maharashtra", "Mumbai");
      statesOfIndia.put("Manipur", "Imphal");
      statesOfIndia.put("Meghalaya", "Shillong");
      statesOfIndia.put("Mizoram", "Aizawl");
      statesOfIndia.put("Nagaland", "Kohima");
      statesOfIndia.put("Odisha", "Bhubaneshwar");
      statesOfIndia.put("Punjab", "Chandigarh");
      statesOfIndia.put("Rajasthan", "Jaipur");
      statesOfIndia.put("Sikkim", "Gangtok");
      statesOfIndia.put("Tamil Nadu", "Chennai");
      statesOfIndia.put("Telangana", "Hyderabad");
      statesOfIndia.put("Tripura", "Agartala");
      statesOfIndia.put("Uttarakhand", "Dehradun");
      statesOfIndia.put("Uttar Pradesh", "Lucknow");
      statesOfIndia.put("West Bengal", "Kolkata");

    }
    return statesOfIndia;
  }

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

    Map<String, String> data = getStatesOfIndia();

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

    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) {
        var myMap = JSON.parse(xmlhttp.responseText);
        processMap(myMap);
      }
    }
    xmlhttp.open("POST", "/ajax_tutorial/IndiaStates", true);
    xmlhttp.setRequestHeader('Content-Type',
        'application/x-www-form-urlencoded');
    xmlhttp.send(null);
  }

  function processMap(myMap) {
    out = "<table border=''>";
    
    for(data in myMap){
      
      out += "<tr><td>" + data + "</td><td>" + myMap[data] + "</td></tr>";
      //out += data + " " + myMap[data] + "<br />";
    }
    
    out += "</table>";
    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 and capitals of India.







Prevoius                                                 Next                                                 Home

No comments:

Post a Comment