Cascading DropDownList Using Ajax, J2ee, Oracle
Step -I
Index.jsp
<%--
Document : Cascading Drop Down List
Created on : 26 Jul, 2013, 7:26:39 PM
Author : snlkjha
Description:
Front end: JSP using JSTL
Middle tier: Java Classes
Database : Oracle 10G
sample table used test123(country,state,dist) one-many-many
MVC has been Follwed.
--%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="Styles/ddl_css.css">
<script language="javascript" src="Script/ajax.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<div id="dd">
<h2 align="center">An Example of Cascading Drop Down List Using Ajax</h2>
<table cellpadding="2px">
<tr>
<td>Country</td>
<td>
<jsp:useBean id="country1" scope="session" class="in.blogspot.snlkjha.classes.Countries"/>
<select id="country" name="country" onchange="showState(this.value);">
<option value="">Select Country</option>
<c:forEach items="${country1.countries}" var="item">
<option value="${item}">${item}</option>
</c:forEach>
</select>
</td>
</tr>
<tr>
<td>State</td>
<td><select id="state" name="state" onchange="showDist(this.value);">
<option value="">Select State</option>
</select>
</td>
</tr>
<tr>
<td>District</td>
<td>
<select id="dist" name="dist">
<option>Select District</option>
</select>
</td>
</tr>
</table>
</div>
</body>
</html>
Stwp-II
ajax.js(JavaScript File withing Script Folder)
function showState(str)
{
var x = document.getElementById("state");
var y = document.getElementById("dist");
var xmlhttp;
while (y.length > 1)
{
y.remove(y.length - 1);
}
if (str === "")
{
while (x.length > 1)
{
x.remove(x.length - 1);
}
return;
}
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)
{
while (x.length > 1)
{
x.remove(x.length - 1);
}
var states = xmlhttp.responseText;
if (states === "") {
alert('There is no state mentioned for this country');
}
var state = states.split(",");
for (var i = 0; state[i]; i++) {
var option = document.createElement("option");
option.text = state[i];
try
{ // for IE earlier than version 8
x.add(option, x.options[null]);
}
catch (e)
{
x.add(option, null);
}
}
}
};
xmlhttp.open("POST", "Populate_State?country=" + str, true);
xmlhttp.send();
}
function showDist(str)
{
var x = document.getElementById("dist");
var xmlhttp;
if (str === "")
{
while (x.length > 1)
{
x.remove(x.length - 1);
}
return;
}
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 dists = xmlhttp.responseText;
if (dists === "") {
alert('There is no district mentioned for this state');
}
var dist = dists.split(",");
while (x.length > 1)
{
x.remove(x.length - 1);
}
for (var i = 0; dist[i]; i++) {
var option = document.createElement("option");
option.text = dist[i];
try
{ // for IE earlier than version 8
x.add(option, x.options[null]);
}
catch (e)
{
x.add(option, null);
}
}
}
};
xmlhttp.open("POST", "Populate_Dist?state=" + str, true);
xmlhttp.send();
}
Step-III
dd_css.css within Style folder
#country{width:500px;}
#dist{width:500px;}
#state{width:500px;}
#name{width:496px;}
table{margin:0 auto 0;}
#dd{width:960px;margin:0 auto 0;}
Step-IV
Java Classes
Connect.java
package in.blogspot.snlkjha.classes;
/**
*
* @author snlkjha
*/
import java.sql.*;
public class Connect {
Connection con=null;
static Connect _instance;
public static Connect getInstance(){
if(_instance==null){
_instance = new Connect();
}
return _instance;
}
public Connection getDBConnection() throws ClassNotFoundException, SQLException {
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","sunil","sunil");
return con;
}
}
Countries.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package in.blogspot.snlkjha.classes;
import java.sql.*;
import java.util.ArrayList;
/**
*
* @author snlkjha
*/
public class Countries {
private ArrayList<String> countries;
public ArrayList<String> getCountries() throws SQLException
{
countries=new ArrayList<String>();
try {
Connection con = Connect.getInstance().getDBConnection();
Statement smt = con.createStatement();
ResultSet rs1 = smt.executeQuery("select distinct country from test123");
while (rs1.next()) {
countries.add(rs1.getString(1));
}
}catch (ClassNotFoundException ex) {
}
return countries;
}
}
Dists.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package in.blogspot.snlkjha.classes;
import java.sql.*;
/**
*
* @author snlkjha
*/
public class Dists {
public String getDist(String country,String state) throws SQLException
{
String dists="";
try {
Connection con = Connect.getInstance().getDBConnection();
Statement smt = con.createStatement();
ResultSet rs1 = smt.executeQuery("select distinct dist from test123 where country='"+country+"' and state='"+state+"'");
while (rs1.next()) {
dists=dists+rs1.getString(1)+",";
}
}catch (ClassNotFoundException ex) {
}
return dists;
}
}
States.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package in.blogspot.snlkjha.classes;
import java.sql.*;
/**
*
* @author snlkjha
*/
public class states {
public String getState(String country) throws SQLException
{
String states="";
Connection con = null;
try {
con = Connect.getInstance().getDBConnection();
Statement smt = con.createStatement();
ResultSet rs1 = smt.executeQuery("select distinct state from test123 where country='"+country+"'");
while (rs1.next()) {
states=states+rs1.getString(1)+",";
}
}catch (ClassNotFoundException ex) {
}
return states;
}
}
Java Servlets
Populate_Dist.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package in.blogspot.snlkjha.servlet;
import in.blogspot.snlkjha.classes.Dists;
import java.io.IOException;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
* @author snlkjha
*/
public class Populate_Dist extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
HttpSession session = request.getSession(true);
String country = (String) session.getAttribute("country");
String state=request.getParameter("state");
String districts=(new Dists()).getDist(country, state);
response.getWriter().print(districts);
} catch (SQLException ex) {
Logger.getLogger(Populate_Dist.class.getName()).log(Level.SEVERE, null, ex);
}
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
}
Populate_State.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package in.blogspot.snlkjha.servlet;
import in.blogspot.snlkjha.classes.states;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* @author snlkjha
*/
public class Populate_State extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession(true);
try {
PrintWriter out = response.getWriter();
String country = request.getParameter("country");
session.setAttribute("country", country);
String s=(new states()).getState(country);
out.print(s);
} catch (SQLException ex) {
Logger.getLogger(Populate_State.class.getName()).log(Level.SEVERE, null, ex);
}
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
}
Output: