Skip to content
Related Articles

Related Articles

Servlet – Pagination with Example

View Discussion
Improve Article
Save Article
  • Last Updated : 14 Feb, 2022

Pagination is a sequence of pages that are connected and have similar content. Pagination is a technique for splitting a list of multiple records into subsists. For example, you search with a keyword on Google and receive tens of thousands of results. It is important to note that even when the content on a section of a page is split into distinct pages, we will still define that as pagination.

Pagination in Java

To divide a large number of records into multiple parts, we use pagination. It allows users to display a part of records only. Loading all records on a single page may take time, so it is always recommended to created pagination. In java, we can develop pagination examples easily. In this pagination example, we are using the MySQL database to fetch records.


Step 1: Create a table in Mysql

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

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


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: Creating a factory class for Getting connections from the DataBase.


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 {
        catch (ClassNotFoundException e) {
    public static ConnectionFactory getInstance()
        return instance;
    public Connection getConnection() throws SQLException, ClassNotFoundException
        Connection connection = DriverManager.getConnection(url, user, password);
        return connection;

Step 4: 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.


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 ( {
                employee = new Employee();
            rs = stmt.executeQuery("SELECT FOUND_ROWS()");
            if (
               this.noOfRecords = rs.getInt(1);
        catch (SQLException e) {
        catch (ClassNotFoundException e) {
            try {
                if (stmt != null)
                if (connection != null)
            catch (SQLException e) {
        return list;
    public int getNoOfRecords() { return noOfRecords; }

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


import a1.Employee;
import a1.EmployeeDAO;
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(); }
    public void doGet(HttpServletRequest request,
                      HttpServletResponse response)
        throws ServletException, IOException
        int page = 1;
        int recordsPerPage = 5;
        if (request.getParameter("page") != null)
            page = Integer.parseInt(
        EmployeeDAO dao = new EmployeeDAO();
        List<Employee> list = dao.viewAllEmployees(
            (page - 1) * 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 file


<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns=""

Step 7: Create a display.jsp file for Displaying records for 5 to 5 records


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
<%@taglib uri="" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
  <table border="1" cellpadding="5" cellspacing="5">
          <th>Emp ID</th>
          <th>Emp Name</th>
          <th>Dept Name</th>
      <c:forEach var="employee" items="${employeeList}">
  <%--For displaying Previous link except for the 1st page --%>
  <c:if test="${currentPage != 1}">
      <td><a href="${currentPage - 1}">Previous</a></td>
  <%--For displaying Page numbers. The when condition does not display
              a link for the current page--%>
  <table border="1" cellpadding="5" cellspacing="5">
          <c:forEach begin="1" end="${noOfPages}" var="i">
                  <c:when test="${currentPage eq i}">
                      <td><a href="${i}">${i}</a></td>
  <%--For displaying Next link --%>
  <c:if test="${currentPage lt noOfPages}">
      <td><a href="${currentPage + 1}">Next</a></td>


Emp Id Emp Name Salary Dp Name
101 Raj 5000 Bca
102 Karan 7000 mca
103 Amit 4000 bcom
104 Manisha 8000 Mba
105 Sakshi 3000 BA

Fetching millions of records from a database consumes almost all the CPU power and memory of the machine. Hence we break millions of records into small chunks showing a limited number of records (say 5 or 10) per page.

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!