Pages Navigation Menu

Coding is much easier than you think

Ajax Cascading DropDownList in JSP & Servlet using JQuery and JSON

 
Dynamic Dependent Select Box using Jquery
 
There are times in a web application where you want to populate a dropdown list based on the value of another drop down list. In this example, we will be creating a dropdown list for favorite spots and favorite player; since this scenario involves in returning complex java objects like lists, maps, etc, so I’m using JSON for this purpose.

In the article on AJAX in Servlet & jsp using JQuery I have demonstrated on returning simple object from servlet to jsp via jquery.

 

Library required

 
Google gson
 

Project Structure

 
Ajax using jquery and json
 

Steps done to set up our Servlet for JSON

 
From the browser perspective: jQuery

jQuery allows you to fire an ajax request via get or post method and expects a JSON object as a response, as described in my previous post the first and second parameter of these method are the url and a key-value pair and the third argument of get method is a function that defines what is to be done with the response that is got back from the Servlet.
 

Recommended reading:

 

Jsp Page

 

<html>
<head>
<title>AJAX in Servlet using JQuery and JSON</title>
<script src="js/jquery-1.11.1.js" type="text/javascript"></script>

<script>
$(document).ready(function() {

$('#sports').change(function(event) {
	var sports = $("select#sports").val();
	$.get('JsonServlet', {
		sportsName : sports
	}, function(response) {

	var select = $('#player');
	select.find('option').remove();
 	  $.each(response, function(index, value) {
	  $('<option>').val(value).text(value).appendTo(select);
      });
	});
	});
});
</script>
</head>
<body>
<h3>AJAX in Servlet using JQuery and JSON</h3>
	Select Favorite Sports:
	<select id="sports">
		<option>Select Sports</option>
		<option value="Football">Football</option>
		<option value="Cricket">Cricket</option>
	</select>
	<br /> <br /> 
	Select Favorite Player:
	<select id="player">
		<option>Select Player</option>
	</select>
</body>
</html>

 
Here jquery will fire an ajax request when the value of the first dropdown is changed(id=”sports”).
 

Another must read:

 
From the server’s perspective: Servlet

In Servlet, I’m going to use a GSON library to convert Java objects (lists, maps etc) to JSON strings that will be parsed by JQuery in the JSP page and will be displayed on the web page and note that I have returned the response back to jsp based on the value of sports parameter which i pass to the servlet via jQuery’s get() method.
 

Servlet

 

package com.action;

import java.io.IOException;
import java.util.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;

public class JsonServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

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

		String sportsName = request.getParameter("sportsName");
		List<String> list = new ArrayList<String>();
		String json = null;

		if (sportsName.equals("Football")) {
			list.add("Lionel Messi");
			list.add("Cristiano Ronaldo");
			list.add("David Beckham");
			list.add("Diego Maradona");
		} else if (sportsName.equals("Cricket")) {
			list.add("Sourav Ganguly");
			list.add("Sachin Tendulkar");
			list.add("Lance Klusener");
			list.add("Michael Bevan");
		} else if (sportsName.equals("Select Sports")) {
			list.add("Select Player");
		}

		json = new Gson().toJson(list);
		response.setContentType("application/json");
		response.getWriter().write(json);
	}
}

 

Web.xml

Servlet mapping should be done in web.xml as shown below
 

<welcome-file-list>
   <welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
   <servlet-name>JsonServlet</servlet-name>
   <servlet-class>com.action.JsonServlet</servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>JsonServlet</servlet-name>
   <url-pattern>/JsonServlet/*</url-pattern>
</servlet-mapping>

 

Demo

 
On selecting ‘Football’ in the first dropdown list
 
Dynamic Dependent Select Box in JSP
 
On selecting ‘Cricket’ in the first dropdown list
 

Other Ajax tutorial from our Blog

 
Dynamic Dependent Select Box in JSP2
 

download
 

Reference

  • jQuery.get()
  • jQuery.each()
  • Wikipedia : JSON
  •  

    About Mohaideen Jamil


    Am currently working as a Struts 2 Developer in a reputed IT Organisations. I can help you with teaching Core java and Struts 2. Follow me on Facebook or Google Plus. If you like my tutorials, consider making a donation to this charity, thanks.

    • Slinjez

      Thank you. This was very helpful.

    • Priyanka Jeeva

      can i get the same by using only jsp

    • Amith Kumar

      Thanks in advance

    • Amith Kumar

      Hi Mohaideen,

      I’m retrieving the values from database based on the selection made in the sports drop down and storing it in a HashMap.

      now how to use ajax and jquery to populate the value in JSp?

      Can you please provide me a solution.

      • Slinjez

        I have tries using maps. It din’t work. I guess it works on list alone.