Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to handle pagination using JSP pages

In this article, we will discuss how pagination can be implemented using JSP pages.

Pagination is a concept or rather a technique to divide the result set into smaller byte size pages for the user to browse through with ease. Pagination by definition is a process to divide content into discreet pages.

Before the progress of Information Technology, pagination was entirely a manual process and print layout was the sole intention. But in today’s world pagination is done mainly to enhance the speed of data fetching in a certain website. Fetching all the data at a time is a slow and resource intensive job, also the user who has to view through the entire list has a poor experience due to amount of data he has to scroll through. Well designed websites always take care of these issues and provide a user friendly experience.

Pagination can be used in server side and client side. Server side pagination is used when

  • Faster initial page loading is required
  • Complex business logic is required in view part
  • There are large data sets

Client side pagination is used when:

  • The data set is small
  • Subsequent page load is faster
  • Full support for sorting and filtering

If you are paginating for cosmetic purpose then it is advised to use client side mechanism. But if you are paginating to reduce initial load time then server side is the best choice. But at the same time proper technique should be implemented on the server side.

Pagination is framework dependent. A regular API used to paginate on a webpage might not work on a Swing application.

Let’s see the ways how we can paginate.

Using a readymade pagination API

This method is useful as well as has its own issues. Firstly a readymade API is easier to find and use the in-built functions to paginate the results. All that needs to be done is give the API details of the number of results and how many pages to display etc. the API code is given below:

<pagination-tag:pager start="<%=start%>" range="<%=range%>" results="<%=results%>"/>
 

The number of results, the start position and the range is all the API needs to do its job and paginate the result. This requires the least work from the developer side. The pagination code is available from the tag library.

The developer needs to know the functions of the API and the rest is taken care by the API. BUT though these APIs reduce the development time, they are not as flexible as might be required at some times.

Creating your own pagination logic

Mostly there are two ways of creating pagination logic. The first way is to fetch all the results and then display them to the user from a cache. The other option is to fetch the result as and when the user accesses them.

This method is commonly known as the greedy fetching.

Greedy Fetching

When paginating greedily a pattern called the ValueListHandler is particularly very useful. This pattern can be reused over several queries and can help the paginating process. An illustration of the class diagram of the ValueListHandler is shown below:

Class diagram

Figure 1: Class diagram

The client employs a ValueListHandler, which in turn accesses a DAO to generate a ValueList. These value lists each contain a few value objects. Each time when the user request for a set of results to be displayed the ValueListHandler, a sub class of ValueList, handles it gracefully. As the ValueList caches the result, the need to go to the database again to fetch the next set of data is eliminated when the user requests it. Each time the ValueListHandler provides the results for the next/previous result pages.

Not-So-Greedy fetching

Let us first discuss the drawback of the above said GREEDY method, only then we can clearly understand the need for this method. Imagine a situation where there are 1, 00,000 records that match a particular query.

Fetching in greedy method the user will have to wait for a very long time until all the records are fetched into the cache of the ValueListHandler. And moreover the values become stale once fetched. That is, if the records are updated once the records are cached then the values may not reflect the updated results. Thus if an application updates data frequently then Greedy fetching may not be the best solution for paging. To overcome these drawbacks, the Not-So-Greedy method is employed. In this method only a limited number of results are fetched at a time. For example an Oracle code is shown:

Listing 1: Sample code displaying oracle query to fetch data for pagination

select *
    from ( select /*+ FIRST_ROWS(n) */ a.*, ROWNUM rwnum
           from ( user query, with order by )a
           where ROWNUM <= :MAX_ROW_TO_FETCH )
    where rwnum>= :MIN_ROW_TO_FETCH; 

Listing 2: Sample displaying a complete pagination example

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" %>
<%@ page import="java.sql.PreparedStatement"  %>
<%@ page import="java.sql.ResultSet" %>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.DriverManager" %>
<%!
public int Converter(String str)
{   
	int convrtr=0;
	if(str==null)
    	{
			str="0";
    	}
	else if((str.trim()).equals("null"))
    	{
			str="0";
    	}
	else if(str.equals(""))
    	{
			str="0";
    	}
	try{
			convrtr=Integer.parseInt(str);
    	}
	catch(Exception e)
    	{
    	}
	return convrtr;
}
%>
<%
	Connection con = null;
	Class.forName("com.mysql.jdbc.Driver").newInstance();
	con = DriverManager.getConnection("jdbc:mysql://localhost:3306/DataBase","uname", "pwd");

	ResultSet rsPgin = null;
	ResultSet rsRwCn = null;
	PreparedStatement psPgintn=null;
	PreparedStatement psRwCn=null;
	
	// Number of records displayed on each page
	int iSwRws=5;  
	// Number of pages index displayed
	int iTotSrhRcrds=10; 
	
	int iTotRslts=Converter(request.getParameter("iTotRslts"));
	int iTotPags=Converter(request.getParameter("iTotPags"));
	int iPagNo=Converter(request.getParameter("iPagNo"));
	int cPagNo=Converter(request.getParameter("cPagNo"));

	int iStRsNo=0;
	int iEnRsNo=0;

	if(iPagNo==0)
    	{
			iPagNo=0;
    	}
	else{
			iPagNo=Math.abs((iPagNo-1)*iSwRws);
    	}
	
    String sqlPgintn="SELECT SQL_CALC_FOUND_ROWS * FROM tableName limit "+iPagNo+","+iSwRws+"";
	psPgintn=con.prepareStatement(sqlPgintn);
	rsPgin=psPgintn.executeQuery();
 	// Count total number of fetched rows
 	String sqlRwCnt="SELECT FOUND_ROWS() as cnt";
	psRwCn=con.prepareStatement(sqlRwCnt);
	rsRwCn=psRwCn.executeQuery();
	
	if(rsRwCn.next())
      {
		iTotRslts=rsRwCn.getInt("cnt");
      }
%>
<html>
	<head>
		<title>Pagination using JSP page</title>
	</head>
<body>
	<form name="frm">
		<input type="hidden" name="iPagNo" value="<%=iPagNo%>">
		<input type="hidden" name="cPagNo" value="<%=cPagNo%>">
		<input type="hidden" name="iSwRws" value="<%=iSwRws%>">
		
		<table width="100%" cellpadding="0" cellspacing="0" border="0" >
		<tr>
		<td>Emp Name</td>
		<td>Emp Batch</td>
		<td>Emp Address</td>
		</tr>
<%
	while(rsPgin.next())
	  {
%>
		<tr>
			<td><%=rsPgin.getString("EmpName")%></td>
			<td><%=rsPgin.getString("EmpBatchs")%></td>
			<td><%=rsPgin.getString("EmpAddress")%></td>
		</tr>
<% 
 	 }
%>
<%
  	// Calculate next record start and end position 
	try{
		if(iTotRslts<(iPagNo+iSwRws))
            {
				iEnRsNo=iTotRslts;
            }
		else
            {
				iEnRsNo=(iPagNo+iSwRws);
            }

			iStRsNo=(iPagNo+1);
			iTotPags=((int)(Math.ceil((double)iTotRslts/iSwRws)));
       	}
	catch(Exception e)
        {
				e.printStackTrace();
        }
%>
<tr>
<td colspan="3">
<div>
<%
     // Create index of pages 
	int i=0;
	int cPge=0;
	if(iTotRslts!=0)
       {
		cPge=((int)(Math.ceil((double)iEnRsNo/(iTotSrhRcrds*iSwRws))));
		int prePageNo=(cPge*iTotSrhRcrds)-((iTotSrhRcrds-1)+iTotSrhRcrds);
		if((cPge*iTotSrhRcrds)-(iTotSrhRcrds)>0)
        	{
        %>
		<a href="index.jsp?iPagNo=<%=prePageNo%>&cPagNo=<%=prePageNo%>"><< Previous</a>
		<%
        }
		
		for(i=((cPge*iTotSrhRcrds)-(iTotSrhRcrds-1));i<=(cPge*iTotSrhRcrds);i++)
        {
			if(i==((iPagNo/iSwRws)+1))
          	{
          	%>
		<a href="index.jsp?iPagNo=<%=i%>" style="cursor:pointer;color:red"><b><%=i%></b></a>
			<%
          	}
			else if(i<=iTotPags)
          	{
          	%>
		<a href="index.jsp?iPagNo=<%=i%>"><%=i%></a>
			<% 
          	}
        }
	
		if(iTotPags>iTotSrhRcrds&& i<iTotPags)
        {
         %>
		<a href="index.jsp?iPagNo=<%=i%>&cPagNo=<%=i%>">>> Next</a>
		<%
        }
      }
      %>
	<b>Rows <%=iStRsNo%> - <%=iEnRsNo%>   Total Result  <%=iTotRslts%></b>
</div>
</td>
</tr>
</table>
</form>
</body>
</html>
<%
try{
	if(psPgintn!=null){
		psPgintn.close();
	}
	if(rsPgin!=null){
		rsPgin.close();
	}	
	if(psRwCn!=null){
		psRwCn.close();
	}
	if(rsRwCn!=null){
		rsRwCn.close();
	}
	if(con!=null){
		con.close();
	}
  }
catch(Exception e)
  {
	e.printStackTrace();
  }
%>
 

Following is another piece of code to demonstrate pagination in a different logic. This pagination is based on mysql.

A finished paginated page is shown below:

Displaying pagination out put

Figure 2: Displaying pagination out put

Conclusion:

So we can conclude that Pagination is a technique to render data in a proper way which is efficient and user friendly. As we know fetching millions of records in one shot from database consumes almost all memory and CPU of the machine, so pagination is used in most of the applications to increase performance. To achieve this, millions of records are broken into small chunks for displaying limited number of records (say 30 or 40) per page. Most of the search engines like Google and others use pagination technique for fetching search result.



Website: www.techalpine.com Have 16 years of experience as a technical architect and software consultant in enterprise application and product development. Have interest in new technology and innovation area along with technical...

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login