Ajax Cascading DropDownList in JSP & Servlet using JQuery and JSON

Posted by Somesh Shinde On Tuesday, 14 February 2017 4 comments

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.


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:
  • AJAX Tooltip in Java Web Application using qTip2 jQuery plugin
  • jQuery form validation using jQuery Validation plugin
  • Pagination in Servlet and JSP using jQuery jTable plugin

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
 
Dynamic Dependent Select Box in JSP2

4 comments:

luis pizarro fuentes said...

en Tomcal xml ?

David Corvalán said...

Don't works...

Sonu07 said...

Please make it using jsp and data we get should retrieve from database.

Unknown said...

very good

Post a Comment