How to do pagination in JSP with Servlet JDBC and MYSQL

How to do pagination in JSP is very interesting concept let see step by step.

What is Pagination?

Pagination in programming refers to dividing an extensive data set into smaller, more manageable chunks called pages. It is commonly used when working with databases or APIs to efficiently handle large amounts of information.

Advantages of Pagination?

Using Pagination large data sets can be managed easily.

It improves performance and reduces system resources

Steps to develop Pagination in JSP Servlet

  1. Set page Size to show data (ex. 10 records per page)
  2. Fetch the total number of records from the database (ex 250 records in the database)
  3. Calculate the total number of pages that can be displayed (ex 25 pages)
  4. Get the Page number From the user (ex page no 5)
  5. Calculate starting value for the page and show data up to page size to the user (ex show record numbers 50 to 60)

Technology Used

  1. MySQL /MariaDB version: 10.4.28
  2. JAVA SE-17
  3. Apache Tomcat 10.1.1

Database Setup

For the database, we used mysql-country-list from GitHub copied countries_detailed.sql and past on our MySQL Database.

The basic fields of the database are as below

The database contains total of 250 records.

JSP Servlet Project SetUp

How to do pagination in JSP Project Explorer
How to do pagination in JSP Project Explorer

Create a folder and file structure as above.

Dependency required

jakarta.servlet.jsp.jstl-3.0.0.jar
jakarta.servlet.jsp.jstl-api-3.0.0.jar
mysql-connector-java-8.0.30.jar

The source code are below

CountryServlet.java

JDBC Code for Pagination

ConnectionFactory.java

This class returns a connection object.

CountryDAO.java

JDBC PreparedStatemnt is used to fetch data from the database.

In the countries_detailed table, we have a total of 250 records we are selecting only a few records based on the calculation. limit is used in SQL query is used to select only a few records.

Model class for Fetching data

This class contains fields related to a database table. We have selected only few columns you can increase or decrease as per need.

Country.jsp Jsp Page to show pagination data

On clicking on each page, it call the servlet URL /country-list.

along with the URL, we pass the query string /country-list?p=2.

p represents the page no based on the page number we calculate from which count selects a record and from where to select it.

In Servlet we calculate the start below

start = (pageNo - 1) * pageSize;

query string p is stored in pageNo and pageSize is defined in Servlet.

Web.xml to Show URL

welcome file tag is used to show the servlet on run.

Result

It will show following output

Download Source Code

Hope you Understand How to do pagination in JSP.