Open In App

Servlet – Pagination with Example

Last Updated : 14 Feb, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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.

Example

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.

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: 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: 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: 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 file

XML




<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                             http://java.sun.com/xml/ns/javaee/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 a display.jsp file 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://java.sun.com/jsp/jstl/core" prefix="c"%>
  
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
  
<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>


Output:

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.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads