The following example code demonstrates how to Display Data from a Database Table Using Servlets.

Here is an example of a program using servlets to display data from a database table in Java.

import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class DisplayDataServlet extends HttpServlet {

  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    Connection connection = null;
    Statement statement = null;
    ResultSet resultSet = null;
    try {
      // Load the JDBC driver
      // Connect to the database
      connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "root", "password");
      // Create a statement
      statement = connection.createStatement();
      // Execute a query
      resultSet = statement.executeQuery("SELECT * FROM employees");
      // Store the result set in the request as an attribute
      request.setAttribute("resultSet", resultSet);
      // Forward the request to the JSP page
      RequestDispatcher dispatcher = request.getRequestDispatcher("/display-data.jsp");
      dispatcher.forward(request, response);
    } catch (Exception e) {
    } finally {
      try {
        // Close the result set
        if (resultSet != null) {
        // Close the statement
        if (statement != null) {
        // Close the connection
        if (connection != null) {
      } catch (Exception e) {

Similarly, here is an example of the JSP page, display-data.jsp.

<!DOCTYPE html>
  <title>Display Data</title>
  <h1>Display Data</h1>
      ResultSet resultSet = (ResultSet) request.getAttribute("resultSet");
      while ( {
      <td><%= resultSet.getInt("id") %></td>
      <td><%= resultSet.getString("name") %></td>
      <td><%= resultSet.getString("email") %></td>

In this example, the DisplayDataServlet class handles GET requests. The servlet loads the JDBC driver, connects to the database, creates a statement, and executes a query to retrieve the data from the employees table. The result set is stored in the request as an attribute and the request is then forwarded to the display-data.jsp page,

Further Reading

Understanding Enterprise Java Beans

Java Practice Exercise