Monday, November 19, 2012

AJAX with Servlets using JQuery and JSON




In my previous post, I explained about making AJAX calls to a servlet from a JSP page and updating a part of the JSP page with the response from the Servlet. That was a very simple example I provided in that post by returning a piece of text from the servlet to JSP to start with, and now in this post I am going to add something more to it by making the servlet return complex Java Objects such as lists, maps, etc. To do this, let us get introduced to JSON(Javascript Object Notation), in addition to JQuery and AJAX. JSON is derived from Javascript for representing simple data structures and associative arrays, called objects. Here in our scenario, we are going to use a JSON library in Servlet to convert Java objects (lists,maps,arrays.etc) to JSON strings that will be parsed by JQuery in the JSP page and will be displayed on the web page.


There are many JSON libraries available that can be used to pass AJAX updates between the server and the client. I am going to use google's gson library in this example. 

Now, let us create a simple JSP page with two drop down lists, one that contains values for countries and the other that is going to be populated with values for states based on the value of country selected in the first drop down list. Whenever the value is selected in the "country" drop down list, the "states" drop down list will be populated with corresponding state values based on the country selected. This has to be done without a page refresh, by making AJAX calls to the servlet on the drop down list change event.

Here are the steps to reproduce in Eclipse,

1. First of all create a "Dynamic Web Project" in Eclipse.
2. Create a new JSP page under "Webcontent" folder and copy paste the below code in it.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>AJAX calls to Servlet using JQuery and JSON</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
    $(document).ready(function() {
        $('#country').change(function(event) {  
        var $country=$("select#country").val();
           $.get('ActionServlet',{countryname:$country},function(responseJson) {   
           var $select = $('#states');                           
               $select.find('option').remove();                          
               $.each(responseJson, function(key, value) {               
                   $('<option>').val(key).text(value).appendTo($select);      
                    });
            });
        });
    });          
</script>
</head>
<body>
<h1>AJAX calls to Servlet using JQuery and JSON</h1>
Select Country:
<select id="country">
<option>Select Country</option>
<option value="India">India</option>
<option value="US">US</option>
</select>
<br/>
<br/>
Select State:
<select id="states">
<option>Select State</option>
</select>
</body>
</html>


3. Download google's GSON library from here and place it in your project's WEB-INF/lib folder.
4. Create a servlet in the name 'ActionServlet' (since I have used this name in the jquery code above') in the src directory. Copy and paste the below code in the doGet() method of the servlet and add the import statement in the header section of the servlet.


import com.google.gson.Gson;

protected void doGet(HttpServletRequest request,   HttpServletResponse response) throws ServletException, IOException {

  String country=request.getParameter("countryname");
  Map<String, String> ind = new LinkedHashMap<String, String>();
    ind.put("1", "New delhi");
    ind.put("2", "Tamil Nadu");
    ind.put("3", "Kerala");
    ind.put("4", "Andhra Pradesh");
    
    Map<String, String> us = new LinkedHashMap<String, String>();
    us.put("1", "Washington");
    us.put("2", "California");
    us.put("3", "Florida");
    us.put("4", "New York");
    String json = null ;
    if(country.equals("India")){
     json= new Gson().toJson(ind);   
    }
    else if(country.equals("US")){
     json=new Gson().toJson(us);  
    }
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(json);       
 }

}


In the above code, we create two maps for two countries, and return the one based on the country parameter passed to the servlet in the AJAX call made by the JQuery's get() method. Here we convert the map objects to json strings in order to send the response back to the JSP page.

5. Make sure you have done servlet mapping properly in web.xml file. An example of this is given below,

<servlet>
    <servlet-name>ActionServlet</servlet-name>
    <servlet-class>ajaxdemo.ActionServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>ActionServlet</servlet-name>
    <url-pattern>/ActionServlet/*</url-pattern>
</servlet-mapping>

In the above code,'ajaxdemo' is the package name in which I have created the servlet. Replace it with your package structure to make the servlet work properly.


Thats it! You are now all set to run the project with Tomcat. When you run this project, the second drop down list will be populated automatically when you change the value in the first drop down list. 
Output Screenshots:
First drop down list changing,


On selecting 'India' in the first drop down list,


On selecting 'US' in the first drop down list,


Please leave your comments and queries about this post in the comment sections in order for me to improve my writing skills and to showcase more useful posts. 

1 comments:

Post a Comment