This Java Servlet/JSP tutorial will guide you how to create a drop down list (or combobox) dynamically with items populated from a database. You will also learn how to implement a dynamic drop down list from the database using AJAX and JQuery.

NOTE: You should not write Java code directly in a JSP page as it’s a very bad practice. Why? If you do so, you mix the code of the server side and client side together which will cause problems in reusing and maintaining the code.

The best practice is separating code between server side and client side as much as possible. In case of implementing a dynamic drop down list with items populated from the database, the code to retrieve to items should be written in a Java Servlet, and the code to fill the drop down list with the items should be written in the JSP page using JSTL tags.

Now, let’s see the steps to create a dynamic drop down list from database with Java Servlet, JSP and JSTL.

 

1. Create Database

Suppose that you want to display items in a drop down list from the following table in a MySQL database:

TableCategory

As you can see, the table category contains two columns category_id and name. So our ultimate goal is to dynamically generate HTML code for the drop down list in the JSP page something like this:

<select name="category">
	<option value="category_id">name</option>
	<option value="category_id">name</option>
	<option value="category_id">name</option>
	...
</select>
 

2. Create Java Model Class



Code for the model class that represents an item in the drop down list is as simple as below:

package net.codejava;

public class Category {
	private int id;
	private String name;

	public Category(int id, String name) {
		super();
		this.id = id;
		this.name = name;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
}
As you can see, this Category class represents a row in the category table.

 

3. Code DAO Class

The DAO class is responsible for retrieving data from the database. In case of our example, it retrieves all rows from the category table and returns a collection of Category objects to the caller. It’s very simple if you are using Hibernate. If you use pure JDBC, here’s a sample DAO class:

package net.codejava;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class CategoryDAO {
	String databaseURL = "jdbc:mysql://localhost:3306/bookstoredb";
	String user = "root";
	String password = "pass";
	
	public List<Category> list() throws SQLException {
		List<Category> listCategory = new ArrayList<>();
		
		try (Connection connection = DriverManager.getConnection(databaseURL, user, password)) {
			String sql = "SELECT * FROM category ORDER BY name";
			Statement statement = connection.createStatement();
			ResultSet result = statement.executeQuery(sql);
			
			while (result.next()) {
				int id = result.getInt("category_id");
				String name = result.getString("name");
				Category category = new Category(id, name);
					
				listCategory.add(category);
			}			
			
		} catch (SQLException ex) {
			ex.printStackTrace();
			throw ex;
		}		
		
		return listCategory;
	}
}
As you can see, the list() method connects to the database, retrieves all rows from the category table and returns a List of Category objects. This collection will be used in the JSP page to render the drop down list dynamically.

 

4. Code Java Servlet Class

The Java servlet class is responsible for receiving request from the client. It invokes the DAO to get a list of items from the database, saves this list as an attribute in the request, and then forwards the request to a JSP page.

Here’s the sample code of the servlet class:

package net.codejava;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/list")
public class ListServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		CategoryDAO dao = new CategoryDAO();

		try {

			List<Category> listCatagory = dao.list();
			request.setAttribute("listCategory", listCatagory);

			RequestDispatcher dispatcher = request.getRequestDispatcher("index.jsp");
			dispatcher.forward(request, response);

		} catch (SQLException e) {
			e.printStackTrace();
			throw new ServletException(e);
		}
	}
}
Here, the key point is setting an attribute in the request to store the list of items which will be then used by the destination JSP page:

List<Category> listCatagory = dao.list();
request.setAttribute("listCategory", listCatagory);
 

5. Code JSP Page

In the JSP page, you can use JSTL’s forEach tag to dynamically generate code for the drop down list like this:

<select name="category">
	<c:forEach items="${listCategory}" var="category">
		<option value="${category.id}">${category.name}</option>
	</c:forEach>
</select>
Note that the value for the attribute items must match the name of the corresponding attribute set in the servlet class. As you can see, the values of the drop down list are the IDs of the categories.

If you want to submit the selected value of this drop down list to the server, wrap the above code inside a form like this:

<form action="list" method="post">
	Select a Category:&nbsp;
	<select name="category">
		<c:forEach items="${listCategory}" var="category">
			<option value="${category.id}">${category.name}</option>
		</c:forEach>
	</select>
	<br/><br/>
	<input type="submit" value="Submit" />
</form>
And implement the doPost() method in the servlet class to handle the form submission as follows:

protected void doPost(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {
	int categoryId = Integer.parseInt(request.getParameter("category"));

	request.setAttribute("selectedCatId", categoryId);

	listCategory(request, response);
}
As you can see, this method reads the value of the drop down list sent the client, stores it as a request’s

attribute, and forwards the request to the same destination page as the doGet() method. Hence the listCategory() method is created to be reused by both doGet() and doPost() methods. The code of the servlet class is now looks like this:

package net.codejava;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/list")
public class ListServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

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

	private void listCategory(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		CategoryDAO dao = new CategoryDAO();

		try {

			List<Category> listCatagory = dao.list();
			request.setAttribute("listCategory", listCatagory);

			RequestDispatcher dispatcher = request.getRequestDispatcher("index.jsp");
			dispatcher.forward(request, response);

		} catch (SQLException e) {
			e.printStackTrace();
			throw new ServletException(e);
		}
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		int categoryId = Integer.parseInt(request.getParameter("category"));

		request.setAttribute("selectedCatId", categoryId);

		listCategory(request, response);
	}
}
To display the selected value in the drop down list after form submission, modify the code that generates the drop down list like this:

<option value="${category.id}" 
	<c:if test="${category.id eq selectedCatId}">selected="selected"</c:if>
	>
	${category.name}
</option>
Here’s the complete code of the JSP page:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<html>
<head>
	<title>Dynamic Drop Down List Demo - CodeJava.net</title>
</head>
<body>

<div align="center">
	<h2>Dynamic Drop Down List Demo</h2>
	<form action="list" method="post">
		Select a Category:&nbsp;
		<select name="category">
			<c:forEach items="${listCategory}" var="category">
				<option value="${category.id}" 
					<c:if test="${category.id eq selectedCatId}">selected="selected"</c:if>
					>
					${category.name}
				</option>
			</c:forEach>
		</select>
		<br/><br/>
		<input type="submit" value="Submit" />
	</form>
</div>
</body>
</html>
Type a URL something like this in a web browser to test:

http://localhost:8080/WebAppName/list

Suppose that the category table already has some rows, you can see the result looks like the following screenshot:

TestDynamicDropDownList

Select an item from the drop down list, and click Submit. You should see the page is refreshed with the selected item is the one you have selected.

 

6. Implement Dynamic Drop Down List with AJAX

In this section, we’re going to guide you how to use AJAX with JSP/Servlet and JQuery to create a dynamic drop down list in a JSP page with items populated from a database.

In the JSP page, add the following HTML code:

<h2>Dynamic Drop Down List (AJAX) Demo</h2>
<button id="buttonLoad">Load</button>
<select id="dropdownlist"></select>
<button id="buttonSubmit">Submit</button>
Initially, the page displays two buttons and an empty drop down list like this:

DropDownListAjaxUnload

Click Load button will populate items for the drop down list via AJAX call to a Java servlet. Then click the Submit button to send the selected value to the server also via AJAX call.

Implement doGet() method for the Servlet class as below:

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

	CategoryDAO dao = new CategoryDAO();

	try {

		List<Category> listCatagory = dao.list();
		String json = new Gson().toJson(listCatagory);

		response.setContentType("application/json");
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write(json);

	} catch (SQLException e) {
		e.printStackTrace();
		throw new ServletException(e);
	}
}
As you can see, the key point here is that the servlet returns a JSON string to the client. We use Gson - an open source Java library to serialize and deserialize Java objects to JSON developed by Google. To use Gson, add the following dependency in your project’s pom.xml file:

<dependency>
  <groupId>com.google.code.gson</groupId>
  <artifactId>gson</artifactId>
  <version>2.8.3</version>
</dependency>
To use JQuery for AJAX, add the following code inside the <head> section of your page:

<script src="http://code.jquery.com/jquery-latest.min.js"></script>
To handle click event for the Load button, add the following Javascript:

<script>
    $(document).on("click", "#buttonLoad", function() {
	$.get("listajax", function(responseJson) {
	    var $select = $("#dropdownlist");
	    $select.find("option").remove();   
	    $.each(responseJson, function(index, category) {
		$("<option>").val(category.id).text(category.name).appendTo($select);
	    });                    

	});
    });
</script>
This JQuery code makes an AJAX call of HTTP GET to the servlet named listajax. On receiving JSON data from the server, it iterates over the items in the response and update HTML accordingly to populate items for the drop down list.

Click the Load button and you can see the drop down list is populated with items from the database like this:

DropDownListAjaxLoaded

Now, write the following Javascript to handle click event of the Submit button:

<script>
    $(document).on("click", "#buttonSubmit", function() {
	var params = {category : $("#dropdownlist option:selected").text()};
	$.post("listajax", $.param(params), function(responseText) {
				alert(responseText);            		
	});
    });
</script>
As you can see, this JQuery code makes a AJAX call of HTTP POST to the servlet listajax with a parameter is the text of the selected item in the drop down list. On receiving a text response from the server, it simply shows a message sent by the server.

Implement code in the server by adding doPost() method to the servlet as following:

protected void doPost(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {
	String category = request.getParameter("category");
	String text = "Server replies: You selected category: " + category;
	response.setContentType("text/plain");
	response.setCharacterEncoding("UTF-8");
	response.getWriter().write(text);
}
As you can see, this method simply reads sent from the client, and sends back a text message.

Select an item in the drop down list and click Submit, you can see a message like this:

ServerResponseMessage

For your reference, the following is complete code of the Java servlet class for AJAX implementation:

package net.codejava;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

@WebServlet("/listajax")
public class ListAjaxServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

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

		CategoryDAO dao = new CategoryDAO();

		try {

			List<Category> listCatagory = dao.list();
			String json = new Gson().toJson(listCatagory);

			response.setContentType("application/json");
			response.setCharacterEncoding("UTF-8");
			response.getWriter().write(json);

		} catch (SQLException e) {
			e.printStackTrace();
			throw new ServletException(e);
		}
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String category = request.getParameter("category");
		String text = "Server replies: You selected category: " + category;
		response.setContentType("text/plain");
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write(text);
	}
}
And the following is complete code of the corresponding JSP page:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<html>
<head>
	<title>Dynamic Drop Down List Demo (AJAX) - CodeJava.net</title>
	<script src="http://code.jquery.com/jquery-latest.min.js"></script>
        <script>
            $(document).on("click", "#buttonLoad", function() {
                $.get("listajax", function(responseJson) {
                    var $select = $("#dropdownlist");
                    $select.find("option").remove();   
                    $.each(responseJson, function(index, category) {
                        $("<option>").val(category.id).text(category.name).appendTo($select);
                    });                    
                    
                });
            });
            
            $(document).on("click", "#buttonSubmit", function() {
            	var params = {category : $("#dropdownlist option:selected").text()};
            	$.post("listajax", $.param(params), function(responseText) {
					alert(responseText);            		
            	});
            });
        </script>	
</head>
<body>
<div align="center">
	<h2>Dynamic Drop Down List (AJAX) Demo</h2>
	<button id="buttonLoad">Load</button> &nbsp;
	<select id="dropdownlist"></select>
	<br/><br/>
	<button id="buttonSubmit">Submit</button>
</div>
</body>
</html>
So far you have learned how to create a dynamic drop down list from database with JSP, Servlet, JSTL and JQuery. We hope you found this tutorial helpful.

 

Other JSP Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.



Add comment

   


Comments 

#15Tania June2021-08-08 14:25
Can you make a searchable drop-down list using jsp?
Quote
#14Ayushi Agrawal2020-10-11 05:26
The first time when I run index.jsp i dont have anything in my drop down. I press submit and then the list comes. Please help!
Quote
#13Nam2020-03-25 22:54
Hi Warren,
The JSP page is invoked via the relative URL /list
Quote
#12Warren2020-03-25 19:21
I cannot see where the JSP calls the doGet() to initialize the drop down list.
Quote
#11sharada2020-02-26 21:42
Do you have JSP-Ajax using hibernate one to many mapping dynamic dropdown list.
Quote