In this tutorial you will learn how to implement pagination in JSP.
Pagination is a technique of dividing the content into several pages. Fetching all the data at a time is time consuming and it also results in poor user experience as the user has to scroll down to view data. So, pagination is used to speed up data fetching because only selected amount of data is fetched form server by user request.
Below I have shared JSP pagination example. It is created using Eclipse IDE and the technologies I have used are JSP, jQuery, AJAX, JSON and MySQL.
JSP Pagination Example
Note: To use jQuery you have to add the jQuery library. You can download it from here. To use JSON here I have used json.simple library. You can download it from here. Make sure you include both of these libraries in your project.
Create a dynamic web project in Eclipse and add following code in respective files.
index.jsp
This page displays the data to user. All pagination logic is written here.
<html> <head> <title>JSP Pagination Example</title> <script src="jquery-1.11.3.js"></script> </head> <body> <script type="text/javascript"> $(document).ready(function(){ var totalRecords; var recordsPerPage=5; var recordsToFetch=recordsPerPage; var totalPages; var currentPage=1; var currentIndex=0; $.get("processRequest.jsp?requestType=countRecords",function(data){ var JSONData=JSON.parse(data); totalRecords=JSONData.count; totalPages=Math.floor(totalRecords/recordsPerPage); if(totalRecords%recordsPerPage!=0){ totalPages++; } if(totalRecords<recordsPerPage){ recordsToFetch=totalRecords%recordsPerPage; } else{ recordsToFetch=recordsPerPage; } $("#page").html("Page "+currentPage+" of "+totalPages); }); $.get("processRequest.jsp?requestType=getRecords¤tIndex="+currentIndex+"&recordsToFetch="+recordsToFetch,function(data){ var JSONData=JSON.parse(data); for(i=0;i<recordsToFetch;++i){ $("#div1").append("<p>"+(currentIndex+1)+". "+JSONData.record[i]+"</p>"); currentIndex++; } if(currentPage==totalPages){ $("#next").hide(); } else{ $("#next").show(); } if(currentPage==1){ $("#back").hide(); } else{ $("#back").show(); } }); $("#next").click(function(){ $("#div1").html(""); currentPage++; if(currentPage==totalPages){ $("#next").hide(); if(totalRecords%recordsPerPage!=0){ recordsToFetch=totalRecords%recordsPerPage; } else{ recordsToFetch=recordsPerPage; } } else{ $("#next").show(); recordsToFetch=recordsPerPage; } if(currentPage==1){ $("#back").hide(); } else{ $("#back").show(); } $.get("processRequest.jsp?requestType=getRecords¤tIndex="+currentIndex+"&recordsToFetch="+recordsToFetch,function(data){ var JSONData=JSON.parse(data); for(i=0;i<recordsToFetch;++i){ $("#div1").append("<p>"+(currentIndex+1)+". "+JSONData.record[i]+"</p>"); currentIndex++; } }); $("#page").html("Page "+currentPage+" of "+totalPages); }); $("#back").click(function(){ $("#div1").html(""); currentPage--; currentIndex=currentIndex-recordsToFetch-recordsPerPage; if(currentPage==totalPages){ $("#next").hide(); recordsToFetch=totalRecords%recordsPerPage; } else{ $("#next").show(); recordsToFetch=recordsPerPage; } if(currentPage==1){ $("#back").hide(); } else{ $("#back").show(); } $.get("processRequest.jsp?requestType=getRecords¤tIndex="+currentIndex+"&recordsToFetch="+recordsToFetch,function(data){ var JSONData=JSON.parse(data); for(i=0;i<recordsToFetch;++i){ $("#div1").append("<p>"+(currentIndex+1)+". "+JSONData.record[i]+"</p>"); currentIndex++; } }); $("#page").html("Page "+currentPage+" of "+totalPages); }); }); </script> <div id="div1"></div><br/> <button id="back">Back</button> <button id="next">Next</button> <p id="page"></p> </body> </html>
processRequest.jsp
This page process request by fetching data.
<%@page import="com.PaginationDAO"%> <% String req=request.getParameter("requestType"); String data=""; if(req.equals("countRecords")){ data=PaginationDAO.countRecords(); } if(req.equals("getRecords")){ String start=request.getParameter("currentIndex"); String total=request.getParameter("recordsToFetch"); data=PaginationDAO.getRecords(start, total); } out.print(data); %>
DBConnection.java
Contains code for database connection.
package com; import java.sql.Connection; import java.sql.DriverManager; public class DBConnection { final static String URL="localhost:3306/"; final static String DATABASE="pagination"; final static String USER="root"; final static String PASS="root"; final static String DATA_TABLE="data"; final static String ID_COL="id"; final static String NAME_COL="name"; public static Connection getCon(){ Connection con=null; try{ Class.forName("com.mysql.jdbc.Driver"); con=DriverManager.getConnection("jdbc:mysql://"+URL+DATABASE,USER,PASS); }catch(Exception e){ e.printStackTrace(); } return con; } }
PaginationDAO.java
Fetch data from database and convert it into JSON format.
package com; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import org.json.simple.JSONArray; import org.json.simple.JSONObject; public class PaginationDAO { public static String countRecords(){ String query="select count(*) from "+DBConnection.DATA_TABLE; int count=0; JSONObject obj=new JSONObject(); try{ Connection con=DBConnection.getCon(); PreparedStatement ps=con.prepareStatement(query); ResultSet rs=ps.executeQuery(); if(rs.next()){ count=rs.getInt(1); obj.put("count",count); } }catch(Exception e){ e.printStackTrace(); } return obj.toString(); } public static String getRecords(String start,String total){ String query="select * from "+DBConnection.DATA_TABLE+" limit "+start+","+total; JSONObject obj=new JSONObject(); JSONArray arr=new JSONArray(); try{ Connection con=DBConnection.getCon(); PreparedStatement ps=con.prepareStatement(query); ResultSet rs=ps.executeQuery(); while(rs.next()){ arr.add(rs.getString(DBConnection.NAME_COL)); } obj.put("record",arr); }catch(Exception e){ e.printStackTrace(); } return obj.toString(); } }
Database
The database table that I have used has following structure.
In this example I am fetching only 5 records at a time from the database and then displaying them. You can change the number of records per page according to you.
Download the project from below link. It also contains the database backup file.
Download Project
If you are facing any difficulty then feel free to ask it by commenting below.
Hello, tried will not run. The PaginationDAO seems to be the problem, cannot figure it out.
Read the ide console, you will get the exact error.
cannot connect to database. No data are displayed on screen. Can you verify the connection?
Check DBConnection.java there is have given all connections related information like db name, username, password, etc.
Hi , its work fine but , there is no data from database only two buttons are showing next and back , i make changes in DBconnection , as per my database , here i am using sql server workbench , can u help me whats the problem
Hi After downloading the project , make changes in dbconnection class , two button are showing only next and back when i click next it is displaying page 3 of undefined. can u please tell me the problem i.
Sorry the download link to this project is not working, can you kindly send it to my mail, thanks…