Home Tutorial Jsp Multiple select dropdown with Ajax

 
 

Share on Google+Share on Google+
Multiple select dropdown with Ajax
Posted on: April 15, 2011 at 12:00 AM
Advertisement
This tutorial explains how to create multiple select dropdown with Ajax in JSP and Servlet . This example is created in eclipse IDE and run on tomcat server.

Multiple select dropdown with Ajax

This tutorial explains how to create multiple select  dropdown with Ajax  in JSP and Servlet . This example is created in eclipse IDE and run on tomcat server. The application directory structure should look like as below, if you are developing the application in Eclipse.

multipleselect_dropdown1.gif

This tutorial applies following steps.

Step 1 :

First we create database and table in mysql that is used in this example.

create database if not exists `multipleselect_dropdown`;

USE `multipleselect_dropdown`;

CREATE TABLE `category` (
`category_id` bigint(11) NOT NULL AUTO_INCREMENT,
`cotegory_name` varchar(100) DEFAULT NULL,
`parent_id` bigint(11) NOT NULL,
PRIMARY KEY (`category_id`)
)

Step 2 :

First we create Dynamic web project "multipleselect_dropdown_withajax" in eclipse IDE .  Again we create "index.jsp" file under WebContent folder. The code of "index.jsp" are given as:

<%@ 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>Multiple select dropdown</title>

</head>

<body>

<li><a href="mutipledropdown">Multiple Select Dropdown</a></li>

</body>

</html>

Step 3 :

Now create pojo class "Category.java"  under  " src/net/roseindia/model" directory . The code of "Category.java" given below :

package net.roseindia.model;

import java.io.Serializable;

public class Category implements Serializable{  
  private Integer categoryId; 
  private String cotegoryName;
  private String parentId;
  
  public void setCategoryId(Integer categoryId) {
	 this.categoryId=categoryId;
   }  
  public Integer getCategoryId() {
	  return categoryId;
   }
  
  public void setCotegoryName(String cotegoryName) {
	   this.cotegoryName = cotegoryName;
   }  
  public String getCotegoryName(){
	  return cotegoryName;
   }
  
  public void setParentId(String parentId) {
	  this.parentId = parentId;
   }
  public String getParentId() {
	 return parentId;
   }	
}

Step 3 :

Now create class  "DbConnection.java" under  " src/net/roseindia/servlet" directory  for Connection from database. The code of  "DbConnection.java" given below :

package net.roseindia.servlet;

import java.sql.*;

public class DbConnection {
 static Connection getConnection(){
	String url = "jdbc:mysql://localhost:3306/";
	String db = "multipleselect_dropdown";
	String driver = "com.mysql.jdbc.Driver";
	String user = "root";
	String pass = "";
	
	Connection conn=null;
	try {
	 Class.forName(driver).newInstance();
	 conn =DriverManager.getConnection(url+db, user, pass);
	 return conn;
	}catch (Exception e) {
	 e.printStackTrace();
	 }
	return conn;
  }
}

Step 3 :

Now create class  "MainCategory.java" under  " src/net/roseindia/servlet" directory . This class used for fetch "main category" list .The code of  "MainCategory.java"  given below:

package net.roseindia.servlet;

import java.sql.*;
import java.util.*;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.roseindia.servlet.DbConnection;

import net.roseindia.model.Category;

public class MainCategory extends HttpServlet{  
  protected void doGet(HttpServletRequest request,
		  HttpServletResponse response)throws ServletException, IOException {
   Connection conn = null;
   Statement stmt=null;
   List categorylist=new ArrayList();
   String sqlqueary="SELECT * FROM category where parent_id=0 ";
   try{
	conn=DbConnection.getConnection();
	stmt = conn.createStatement();
	ResultSet rs = stmt.executeQuery(sqlqueary);
	while (rs.next()) {
	 Category category=new Category();
	 category.setCategoryId(rs.getInt(1));
	 category.setCotegoryName(rs.getString(2));
	 category.setParentId(rs.getString(3));
	 categorylist.add(category);
	}	
	stmt.close();
	conn.close();
   }catch (SQLException s){
	 System.out.println("SQL statement is not executed!");
   }
   
  request.setAttribute("categorylist", categorylist);
  RequestDispatcher dispatcher=getServletContext()
  .getRequestDispatcher("/mutipleselect_dropdown.jsp");
  dispatcher.forward(request, response);
 }
}

Step 4 :

Now create class  "SubCategory.java" under  " src/net/roseindia/servlet" directory .This class used for fetch "sub category" list .The code of  "SubCategory.java" class given below :

package net.roseindia.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.roseindia.model.Category;

public class SubCategory extends HttpServlet{
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {
	  String allSelectedCategoryId=request.getParameter("allcategoryid");
	  Connection conn = null;
	  Statement stmt=null;
	  List categorylist=new ArrayList();
	  
	  if(allSelectedCategoryId!=null && !allSelectedCategoryId.equals("")){
		String[] allcategoryid;
		allcategoryid = allSelectedCategoryId.split(",");
		try{
		 conn=DbConnection.getConnection();
		 for(int i =0; i < allcategoryid.length ; i++){
		  try{
		   stmt = conn.createStatement();
		   String sqlqueary="SELECT * FROM category where parent_id="+allcategoryid[i];
		   ResultSet rs = stmt.executeQuery(sqlqueary);
		   while (rs.next()){
			 Category category=new Category();
			 category.setCategoryId(rs.getInt(1));
			 category.setCotegoryName(rs.getString(2));
			 category.setParentId(rs.getString(3));
			 categorylist.add(category);
		   }
		  stmt.close();
		 }catch (SQLException s){
		  System.out.println("SQL statement is not executed!");
		}
	   }
	   conn.close();
	  }catch (Exception e) {
	   e.printStackTrace();
	  }
	 }
	request.setAttribute("categorylist", categorylist);
	RequestDispatcher dispatcher=getServletContext().
	getRequestDispatcher("/subcategory.jsp");
	dispatcher.forward(request, response);
  }
}

Step 5:

Now create class  "SubSubCategory.java" under  " src/net/roseindia/servlet" directory .This class used for fetch "sub sub category" list .The code of  "SubSubCategory.java" class given below : 

package net.roseindia.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.roseindia.model.Category;

public class SubSubCategory extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) 
throws ServletException, IOException {
  String allSelectedCategoryId=request.getParameter("allcategoryid");
  Connection conn = null;
  Statement stmt=null;
  List categorylist=new ArrayList();
  if(allSelectedCategoryId!=null && !allSelectedCategoryId.equals("")){
  String[] allcategoryid;
  allcategoryid = allSelectedCategoryId.split(",");
  try{
	conn=DbConnection.getConnection();
	for(int i =0; i < allcategoryid.length ; i++){
	try{
	 stmt = conn.createStatement();
	 String sqlqueary="SELECT * FROM category where parent_id="+allcategoryid[i];
	 ResultSet rs = stmt.executeQuery(sqlqueary);
	 while (rs.next()) {
		 Category category=new Category();
		 category.setCategoryId(rs.getInt(1));
		 category.setCotegoryName(rs.getString(2));
		 category.setParentId(rs.getString(3));
		 categorylist.add(category);
	  }
	 stmt.close();
	}catch (SQLException s){
	  System.out.println("SQL statement is not executed!");
	    }
	   }
	   conn.close();
	   }catch (Exception e) {
		   e.printStackTrace();
	   }
	}
  request.setAttribute("categorylist", categorylist);
  RequestDispatcher dispatcher=getServletContext()
  .getRequestDispatcher("/subsubcategory.jsp");
  dispatcher.forward(request, response);
 }
}

Step 6:

Now create "mutipleselect_dropdown.jsp"  jsp file under WebContent folder. This file used for displays all multiple select dropdown.The code of "mutipleselect_dropdown.jsp"  given below as:

<%@page import="java.io.*,javax.servlet.*,javax.servlet.http.*,java.sql.*,java.util.*" %>

<%@page import="net.roseindia.model.Category;" %>

<%

List<Category> categorylist=(ArrayList)(request.getAttribute("categorylist"));

%>

<%@ 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>

<SCRIPT LANGUAGE="JavaScript">

//....sub category..start.......

function changeCategoryValue(){

var allseleted="";

for (i=0; i<document.form1.Sel1.length;i++){

if(document.form1.Sel1[i].selected)

allseleted+=", "+document.form1.Sel1[i].value;

}

allseleted=allseleted.substring(1);

getSubCategory(allseleted);

}

function getSubCategory(allseleted)

{

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)

{

setSubCategory(xmlhttp.responseText);

}

}

xmlhttp.open("GET","subcategory?allcategoryid="+allseleted,true);

xmlhttp.send();

}

function setSubCategory(data) {

document.getElementById("subcategorylabel").innerHTML ="Sub Category :";

document.getElementById("subcategory").innerHTML = data;

}

//..........sub category..end......

//....sub..sub category..start.....

function changeSubCategoryValue(){

var allseleted="";

for (i=0; i<document.form1.Sel2.length;i++) {

if (document.form1.Sel2[i].selected)

allseleted+=", "+document.form1.Sel2[i].value;

}

allseleted=allseleted.substring(1);

getSubSubCategory(allseleted);

}

function getSubSubCategory(str)

{

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)

{

setSubSubCategory(xmlhttp.responseText);

}

}

xmlhttp.open("GET","subsubcategory?allcategoryid="+str,true);

xmlhttp.send();

}

function setSubSubCategory(message) {

document.getElementById("subsubcategory").innerHTML = message;

document.getElementById("subsubcategorylabel").innerHTML ="Sub Sub Category :";

}

//......sub..sub category..start....

</SCRIPT>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

<title>Multiple select dropdown</title>

</head>

<body>

<h2 align="center" >Multiple Select Dropdown</h2>

<hr width="350" >

<form name=form1>

<table align="center" >

<tr>

<td>Category :</td>

<td>

<select multiple="multiple" size="3" name=Sel1 onChange="changeCategoryValue()" >

<%

Iterator<Category> iterator = categorylist.iterator();

while(iterator. hasNext()){

Category category=iterator.next();

%>

<option value="<%=category.getCategoryId()%>" ><%=category.getCotegoryName()%>

</option>

<%

}

%>

</select>

</td>

</tr>

<tr>

<td><label id="subcategorylabel" ></label> </td>

<td>

<div id="subcategory" ></div>

</td>

</tr>

<tr>

<td><label id="subsubcategorylabel" ></label></td>

<td>

<div id="subsubcategory"></div>

</td>

</tr>

</table>

</form>

</body>

</html>

Step 7:

Now create "subcategory.jsp"  jsp file under WebContent folder. The code of "subcategory.jsp"  given below as:

<%@page import="java.util.Enumeration,java.util.*" %>

<%@page import="net.roseindia.model.Category;" %>

<%

List<Category> categorylist=(ArrayList)(request.getAttribute("categorylist"));

%>

<%@ 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>Multiple select dropdown</title>

</head>

<body>

<td>

<select multiple="multiple" size="3" name=Sel2 onchange="changeSubCategoryValue()" >

<%

Iterator<Category> iterator = categorylist.iterator();

while(iterator. hasNext()){

Category category=iterator.next();

%>

<option value="<%=category.getCategoryId()%>" >

<%=category.getCotegoryName()%>

</option>

<%

}

%>

</select>

</td>

Step 8:

Now create "subsubcategory.jsp"  jsp file under WebContent folder. The code of "subsubcategory.jsp"  given below as:

<%@page import="java.util.Enumeration,java.util.*" %>

<%@page import="net.roseindia.model.Category;" %>

<%

List<Category> categorylist=(ArrayList)(request.getAttribute("categorylist"));

%>

<%@ 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>Multiple select dropdown</title>

</head>

<body>

<td>

<select multiple="multiple" size="3" >

<%

Iterator<Category> iterator = categorylist.iterator();

while(iterator. hasNext()){

Category category=iterator.next();

%>

<option value="<%=category.getCategoryId()%>" >

<%=category.getCotegoryName()%>

</option>

<%

}

%>

</select>

</td>

</body>

</html>

Step 9:

Now open "web.xml" file and modify as:

<?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"

xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"

xsi:schemaLocation="http://java.sun.com/xml/ns/javaee

http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">

<display-name>multiple_dropdown_withajax</display-name>

<welcome-file-list>

<welcome-file>index.jsp</welcome-file>

</welcome-file-list>

<servlet>

<servlet-name>MainCategory</servlet-name>

<servlet-class>net.roseindia.servlet.MainCategory</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>MainCategory</servlet-name>

<url-pattern>/mutipledropdown</url-pattern>

</servlet-mapping>

<servlet>

<servlet-name>SubCategory</servlet-name>

<servlet-class>net.roseindia.servlet.SubCategory</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>SubCategory</servlet-name>

<url-pattern>/subcategory</url-pattern>

</servlet-mapping>

<servlet>

<servlet-name>SubSubCategory</servlet-name>

<servlet-class>net.roseindia.servlet.SubSubCategory</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>SubSubCategory</servlet-name>

<url-pattern>/subsubcategory</url-pattern>

</servlet-mapping>

</web-app>

Step 10 :

Now download "mysql-connector-java-5.0.5.jar" jar file and paste under  "WebContent/WEB-INF/lib" directory .

Step 11 :

When run  this application on tomcat server displays output as:

multipleselect_dropdown2.gif

When click hyperlink "Multiple Select Dropdown"  displays output as:

multipleselect_dropdown3.gif

Again when select one or more category in dropdown then displays sub category list as:

multipleselect_dropdown4.gif

Again when select  one or more 'sub category'  then displays 'sub sub category' list as:

multipleselect_dropdown5.gif

Download Code

Download example code

Advertisement

Related Tags for Multiple select dropdown with Ajax:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: April 15, 2011

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com