Servlet - Pagination with Example

Last Updated : 18 May, 2026

Pagination in Servlets is a technique used to split large datasets into multiple pages and display only a limited number of records per page. It improves application performance by reducing server load and enhances user experience by making data easier to navigate.

  • Breaks large datasets into smaller pages
  • Improves response time and reduces database load
  • Widely used in search results, admin panels, and reports

Why Pagination is Important?

  • Prevents loading thousands of records at once
  • Reduces memory consumption on server
  • Improves UI performance and readability
  • Enhances scalability of web applications

Working of Pagination

Pagination in Servlet works by dividing records into pages using two main values:

  • Page number (page) -> tells which page user is currently viewing
  • Records per page (limit) -> tells how many records should be shown on one page

Formula: Instead of loading all records at once, Servlet uses this formula to calculate the starting point of data for the current page. It fetches only the required set of records from the database, making the application faster and more efficient.

Start Index=(page−1)×recordsPerPage

Steps To Implements Servlet Pagination with MySQL

Follow these steps to use Pagination functionality in your Servlet Application.

Step 1: Create Table in MySQL

Create a employee table in Mysql

create table employee(
empid int(11),
empname varchar(20),
empsalary int(11),
empdept varchar(20)
);

Step 2: JavaBean Class (Employee)

Create a JavaBean class for setting values to the database and getting values from the database.

Java
public class Employee {
    int employeeId;
    String employeeName;
    int salary;
    String deptName;

    public String getDeptName() { return deptName; }

    public void setDeptName(String deptName)
    {
        this.deptName = deptName;
    }

    public int getEmployeeId() { return employeeId; }

    public void setEmployeeId(int employeeId)
    {
        this.employeeId = employeeId;
    }

    public String getEmployeeName() { return employeeName; }

    public void setEmployeeName(String employeeName)
    {
        this.employeeName = employeeName;
    }

    public int getSalary() { return salary; }

    public void setSalary(int salary)
    {
        this.salary = salary;
    }
}

Step 3: Connection Factory Class

Creating a factory class for Getting connections from the DataBase.

Java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class ConnectionFactory {

    // static reference to itself
    private static ConnectionFactory instance = new ConnectionFactory();

    String url = "jdbc:mysql://localhost:3306/ashok";
    String user = "root";
    String password = "";
    String driverClass = "com.mysql.jdbc.Driver";

    // private constructor
    private ConnectionFactory()
    {
        try {
            Class.forName(driverClass);
        }
        catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static ConnectionFactory getInstance()
    {
        return instance;
    }

    public Connection getConnection() throws SQLException, ClassNotFoundException
    {
        Connection connection = DriverManager.getConnection(url, user, password);
        return connection;
    }
}

Step 4: DAO Class (EmployeeDAO)

Creating a Dao class for creating a Factory class Object and calling in that method. And create a query and set it to JavaBean object and added to ArrayList Object.

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

public class EmployeeDAO {

    Connection connection;
    Statement stmt;
  
    private int noOfRecords;
    public EmployeeDAO() {}

    private static Connection getConnection() throws SQLException, ClassNotFoundException
    {
        Connection con = ConnectionFactory.getInstance().getConnection();
        return con;
    }

    public List<Employee> viewAllEmployees(int offset, int noOfRecords)
    {
        String query = "select SQL_CALC_FOUND_ROWS * from employee limit " + offset + ", " + noOfRecords;
        List<Employee> list = new ArrayList<Employee>();
        Employee employee = null;
        try {
            connection = getConnection();
            stmt = connection.createStatement();
            ResultSet rs = stmt.executeQuery(query);
            while (rs.next()) {
                employee = new Employee();
                employee.setEmployeeId(rs.getInt(1));
                employee.setEmployeeName(rs.getString(2));
                employee.setSalary(rs.getInt(3));
                employee.setDeptName(rs.getString(4));
                list.add(employee);
            }

            rs.close();
            rs = stmt.executeQuery("SELECT FOUND_ROWS()");

            if (rs.next())
               this.noOfRecords = rs.getInt(1);
        }
        catch (SQLException e) {
            e.printStackTrace();
        }
        catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        finally
        {
            try {
                if (stmt != null)
                    stmt.close();
                if (connection != null)
                    connection.close();
            }
            catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return list;
    }
    public int getNoOfRecords() { return noOfRecords; }
}

Step 5: Servlet Class (EmployeeServlet)

Create a Servlet class and create a DAO class Object and call the method and Forwarded to display.jsp page

Java
import a1.Employee;
import a1.EmployeeDAO;
import java.io.IOException;
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;

public class EmployeeServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;
    public EmployeeServlet() { super(); }

    @Override
    public void doGet(HttpServletRequest request,
                      HttpServletResponse response)
        throws ServletException, IOException
    {
        int page = 1;
        int recordsPerPage = 5;
        if (request.getParameter("page") != null)
            page = Integer.parseInt(
                request.getParameter("page"));
        EmployeeDAO dao = new EmployeeDAO();
        List<Employee> list = dao.viewAllEmployees(
            (page - 1) * recordsPerPage,
            recordsPerPage);
        int noOfRecords = dao.getNoOfRecords();
        int noOfPages = (int)Math.ceil(noOfRecords * 1.0
                                       / recordsPerPage);
        request.setAttribute("employeeList", list);
        request.setAttribute("noOfPages", noOfPages);
        request.setAttribute("currentPage", page);
        RequestDispatcher view
            = request.getRequestDispatcher("display.jsp");
        view.forward(request, response);
    }
}

Step 6: Configure web.xml

Maps servlet to URL pattern.

XML
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://www.oracle.com/webfolder/technetwork/jsc/xml/ns/javaee/index.html"
         xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://www.oracle.com/webfolder/technetwork/jsc/xml/ns/javaee/index.html
                             http://www.oracle.com/webfolder/technetwork/jsc/xml/ns/javaee/index.html/web-app_3_0.xsd">

   <servlet>
       <servlet-name>EmployeeServlet</servlet-name>
       <servlet-class>a2.EmployeeServlet</servlet-class>
   </servlet>

   <servlet-mapping>
       <servlet-name>EmployeeServlet</servlet-name>
       <url-pattern>/employee.do</url-pattern>
   </servlet-mapping>

   <session-config>
       <session-timeout>30</session-timeout>
   </session-config>

</web-app>

Step 7: Create display.jsp

It is used for Displaying records for 5 to 5 records

HTML
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"

  pageEncoding="ISO-8859-1"%>

<%@taglib uri="http://www.oracle.com/technetwork/java/index.html" prefix="c"%>

<!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>Employees</title>
</head>

<body>
  <table border="1" cellpadding="5" cellspacing="5">
      <tr>
          <th>Emp ID</th>
          <th>Emp Name</th>
          <th>Salary</th>
          <th>Dept Name</th>
      </tr>

      <c:forEach var="employee" items="${employeeList}">
          <tr>
              <td>${employee.employeeId}</td>
              <td>${employee.employeeName}</td>
              <td>${employee.salary}</td>
              <td>${employee.deptName}</td>
          </tr>
      </c:forEach>

  </table>

  <%--For displaying Previous link except for the 1st page --%>
  <c:if test="${currentPage != 1}">
      <td><a href="employee.do?page=${currentPage - 1}">Previous</a></td>
  </c:if>

  <%--For displaying Page numbers. The when condition does not display
              a link for the current page--%>

  <table border="1" cellpadding="5" cellspacing="5">
      <tr>
          <c:forEach begin="1" end="${noOfPages}" var="i">
              <c:choose>
                  <c:when test="${currentPage eq i}">
                      <td>${i}</td>
                  </c:when>
                  <c:otherwise>
                      <td><a href="employee.do?page=${i}">${i}</a></td>
                  </c:otherwise>
              </c:choose>
          </c:forEach>
      </tr>
  </table>

  <%--For displaying Next link --%>

  <c:if test="${currentPage lt noOfPages}">
      <td><a href="employee.do?page=${currentPage + 1}">Next</a></td>
  </c:if>

</body>

</html>

Step 8: Run the Application

  • Start Apache Tomcat Server
  • Deploy the project in IDE (Eclipse/IntelliJ)
  • Run the application
  • Open browser and hit:

http://localhost:8080/YourProjectName/employee.do

Output:

Emp IdEmp NameSalaryDp Name
101Raj5000Bca
102Karan7000mca
103Amit4000bcom
104Manisha8000Mba
105Sakshi3000BA

Explanation: The application fetches employee records from the MySQL database in small chunks using pagination logic in the Servlet. Based on the current page number, the DAO calculates the starting index and retrieves only a limited number of records using SQL LIMIT. These records are then forwarded to the JSP page for display with navigation links (Previous, Next, and page numbers).

Comment