Dynamic Drop Down List with Struts 2 and AJAX

In this tutorial session we will create simple application to load the drop down list options dynamically from the server side. Also we will load one drop down list based on the selection of another drop down list.

We use AJAX, JQuery, Struts2 and json methodologies to achieve this. Also we assume the basic setup for struts2 is already ready. (i.e) All necessary jar files placed in right place. If you want more info please refer the Struts 2 Hello World application.

Create a simple html file with the below content.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>

<head>
    <script src="js/jquery-1.11.1.min.js"></script>
    <script>
        $(function () {
            $('#state').html('');
            $.getJSON("readStates", function (res) {
                for (var i = 0; i < res.states.length; i++) {
                    $('#state').append(
                        '<option value=' + res.states[i] + '>' + res.states[i] + '</option>');
                }
            });

            $("#state").change(
                function () {
                    $('#district').html('');
                    var state = {
                        "state": $("#state").val()
                    };
                    $.ajax({
                        url: "readDistricts",
                        data: JSON.stringify(state),
                        dataType: 'json',
                        contentType: 'application/json',
                        type: 'POST',
                        async: true,
                        success: function (res) {
                            console.log(res.districts.length);
                            for (var i = 0; i < res.districts.length; i++) {
                                console.log(" " + res.districts[i]);
                                $('#district').append(
                                    '<option value=' + res.districts[i] + '>' + res.districts[i] + '</option>');
                            }
                        }
                    });
                });
        });
    </script>
</head>

<body>
    <h3>Struts 2 Dynamic Drop down List</h3>
    State :
    <select id="state"></select>District :
    <select id="district"></select>
</body>

</html>

Create struts.xml file with the below content and place it under class folder root path.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
    <package name="default" namespace="/" extends="json-default">
        <interceptors>
            <interceptor-stack name="defaultStack">
                <interceptor-ref name="json">
                    <param name="enableSMD">true</param>
                </interceptor-ref>
            </interceptor-stack>
        </interceptors>
        <default-interceptor-ref name="defaultStack" />

        <action name="readDistricts" class="com.rajesh.struts2.ReadData" method="dbDistricts">
            <result type="json"></result>
        </action>

        <action name="readStates" class="com.rajesh.struts2.ReadData" method="dbStates">
            <result type="json"></result>
        </action>

    </package>
</struts>

As we are sending and receiving the data as json object we need to enable the json option in the struts.xml file. So implement a custom interceptor and json result type as above. (To do this struts2-json-plugin.jar is required)

See our web.xml file below.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
	id="WebApp_ID" version="3.0">
	<display-name>HelloStruts</display-name>

	<filter>
		<filter-name>struts2</filter-name>
		<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
	</filter>

	<filter-mapping>
		<filter-name>struts2</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

	<welcome-file-list>
		<welcome-file>/index.html</welcome-file>
	</welcome-file-list>
</web-app>

Also create the java class ReadData which contains the business logic with the below code and place under com.rajesh.struts2 package in the class folder.

package com.rajesh.struts2;

import com.opensymphony.xwork2.ActionSupport;

public class ReadData extends ActionSupport {

    private static final long serialVersionUID = -8819352697303500472L;

    private String state, district;
    private String states[], districts[];

    public String[] getDistricts() {
        return districts;
    }

    public void setDistricts(String[] districts) {
        this.districts = districts;
    }

    public String[] getStates() {
        return states;
    }

    public void setStates(String[] states) {
        this.states = states;
    }

    public String getState() {
        return state;
    }

    public void setState(String state) {
        System.out.println("Inside Setter " + state);
        this.state = state;
    }

    public String getDistrict() {
        return district;
    }

    public void setDistrict(String district) {
        this.district = district;
    }

    public String dbDistricts() {
        System.out.println("Getting Districts for " + state);
        //Do the database code or business logic here.
        districts = new String[5];
        if (state.equalsIgnoreCase("tamilnadu")) {
            districts[0] = "chennai";
            districts[1] = "madurai";
            districts[2] = "trichy";
            districts[3] = "Covai";
            districts[4] = "Pudukkottai";
        } else if (state.equalsIgnoreCase("kerala")) {
            districts[0] = "allappey";
            districts[1] = "trivandrum";
            districts[2] = "kozhikkode";
            districts[3] = "District 4";
            districts[4] = "District 5";
        } else if (state.equalsIgnoreCase("karnataka")) {
            districts[0] = "bangalore";
            districts[1] = "Bommanahalli";
            districts[2] = "Mysore";
            districts[3] = "District 4";
            districts[4] = "District 5";
        } else {
            districts[0] = "District 1";
            districts[1] = "District 2";
            districts[2] = "District 3";
            districts[3] = "District 4";
            districts[4] = "District 5";
        }
        return SUCCESS;
    }

    public String dbStates() {
        //Do the database code or business logic here.
        states = new String[5];
        states[0] = "tamilnadu";
        states[1] = "kerala";
        states[2] = "karnataka";
        states[3] = "delhi";
        states[4] = "kashmir";
        return SUCCESS;
    }
}

See the complete structure of the folder below.

dynamic_dd_structure

That’s all. Simply run the program as below and see the result in action.

http://localhost:8080/DynamicData/

dynamic_dd

For the above example I have created a complete .war file with source code. Download and just place under Apache web apps folder and run.
[wpdm_package id=’552′]
If you face any issues while execution please post in comments or send me email to rajeshmepco@gmail.com

5 Comments

Add a Comment

Your email address will not be published. Required fields are marked *