Paging a JSP page source code -required URGENT-

Posted on 2001-06-18
Last Modified: 2007-12-19
Paging a JSP page source code -required URGENT-
I need to paging some JSP pages in 20 item.. I DONT KNOW HOW!
i need a source code as example!
Question by:btretzanor

Expert Comment

ID: 6204119
//    On your JSP page:

         Vector vClients = (Vector)request.getAttribute("clients");
         int pageNo = Integer.parseInt((String)request.getAttribute("page"));
         int totalPages = Integer.parseInt((String)request.getAttribute("totalPages"));
         int totalCount = Integer.parseInt((String)request.getAttribute("totalCount"));
         boolean hasMorePage = (pageNo < totalPages);

<FORM name="FORM1" method=post action="/servlets/myServlet">
       <% //-- To hold paging logic -- %>
      <input type=hidden name="page" value="1">

      <center><FONT color=black face=Arial size=2>Search returned <b><%= totalCount %></b> results<% if(vClients.size() != 0) { %> (Page <b><%= pageNo %></b> of <b><%= totalPages %></b>)<%}%></FONT><center><br>

// display l20 customers from vClients:
     <% //--------------------- Table Data -----------------%>
          // Display message if there were no matches.
            out.println("<TR bgColor=lightgoldenrodyellow>" +
                        "  <TD colspan=8><b><FONT face=Arial size=2>NO CLIENTS MATCHED YOUR SEARCH CRITERIA.</FONT></b></TD>");

          int row=1;
          Iterator it = vClients.iterator();
            cInfo = (BasicClientInfoBean);

        <TR bgColor=<%  if ( (row%2) == 1 ) {%>lightgoldenrodyellow
                    <%} else {%>aliceblue <%}%> >
          <TD><jsp:getProperty name="cInfo" property="firstname" />&nbsp;<jsp:getProperty name="cInfo" property="lastname" />
          } // end of while loop


     //display nav bar at the bottom as:

                       <% if(pageNo>1) { %>
                  <b><FONT face=Arial size=2 color=white>
                  <a href="javascript:onclick=history.back()" onmouseout="window.status='';return true" onmouseover ="window.status='Previous Page';return true">
                  Previous Page</a></FONT></b>
                <% if(hasMorePage) { %>
                  <% if(pageNo>1) {%>
                  <FONT face=Arial size=2 color=white><b>
                <a href="javascript:onclick=nextPage(<%= pageNo+1 %>)" onmouseout="window.status='';return true" onmouseover ="window.status='Next Page';return true">
                  Next Page</a></b></FONT>

// where nextPage () is javascript on the page:

  function nextPage(page){

Expert Comment

ID: 6204152
// in your myServlet:
 int  NUM_PER_PAGE = 20;
 public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

      // A vector of BasicClientInfoBean objects.
      Vector vClients = new Vector();

     // Page numbering.
      int page = 1;
        page = Integer.parseInt(request.getParameter("page"));
      }catch(Exception e){
            // default to 1.

           sql ="select ....";
           // TODO: get DB connection:
               con = getconnection...;
           Statement stmt = con.createStatement();
          ResultSet  rs = stmt.executeQuery(makeSQL());
           int count=0;
             while( ){
                    count ++;
                    //add those client that are on page'th page:
                    if(((page - 1)* NUM_PER_PAGE + 1 <= count) && (count <= page * NUM_PER_PAGE)){
                         BasicClientInfoBean client = new BasicClientInfoBean();
      }catch(SQLException e){
          System.err.println("GroupServlet ->searchGroup()-> error:" + e.getMessage());

       // Get the number of pages.
      int total = vClients.size();
      int totalPages = (int)Math.ceil((double)total/NUM_PER_PAGE);
      // Set request objects for use in the result screen.
      request.setAttribute("clients", vClients);
      request.setAttribute("page", "" + page);
      request.setAttribute("totalPages", Integer.toString(totalPages));
      request.setAttribute("totalCount", Integer.toString(total));

Expert Comment

ID: 6204156
above code is not pretended to be working, but
it is extracted from my working code and
intended to give you the basic idea.
Hope it helps.

Accepted Solution

rajendra_rathod earned 200 total points
ID: 6205955
Here is the JSP pagination I have used for my project. It has used JavaBean to fetch Records from the database.
On JSP page u will see Next and Previous links through which u can navigate.

Processing is as follows
When user first time come to the page the query will be fired and data will be stored in Vector which again consist of vectors.When the user clicks on Next or Previous the index of the vector gets changed and further data will be displayed.This helps us not to contact database again and again for data fetching.
Middle part of the code consist of avoiding the repeatating values to be displayed.

U can define How many Records u like to display?
If no. of records from the database are less than specified in JSP to display then the links will be disabled.

It is some what difficult to understand for the first time but if u go carefully u will understand it since we are using this in our live project to develop reports.

This is the JSP page and below it is the JavaBean

In case of any doubt feel free to contact.
<title>Credit Checks Performed</title>
<%@ page import = "java.sql.*,java.util.*,ReportBean" errorPage = "error.jsp"%>
<jsp:useBean id = "reportbean" scope = "page" class = "ReportBean"/>

   int iRows,iRecordNumber,iTotalCount = 0;
   Vector vectInner,vectOuter,vectComparison;
   String strCcDate,strSessionValue,strCustName = "",strNextCustName = "";
   final int iRecOnPage = 25;
   String strDynamicPart,strQuery,strCriteria;
<% int iFlag = 0; %>
<% String strDisplay = ""; %>
      /* This part is executed only once when user first enters. In this depending upon the
            selection criteria vector is populated using ReportBean

      if (request.getParameter("Navigation") != null)
                  vectInner = new Vector();
            vectOuter = new Vector();
                  String  strQuery = " SELECT *  " +
                                                               " FROM " +
                                                               " emp "
                  try {
                        if (vectOuter.isEmpty())
                  } catch (Exception e) {
                        throw new Exception ("Server Error !! Please Try After Some Time");
      } // end of (request.getParameter("Navigation")!=null)
<h2 class pagetitle>Credit Checks Performed </h2>
<h2 class pagetitle><%= strCriteria %></h2>
<% if (iFlag==0) {%>
                  <table border="1" cellpadding="3" cellspacing="0" id="SearchDisplayTbl" width = "100%">
                        <TH class=searchdisplay align=left>  Customer Name</TH>
                        <TH class=searchdisplay align=left>  Account No </TH>
                        <TH class=searchdisplay align=left>  DUNNS Number</TH>
                        <TH class=searchdisplay align=left>  Town</TH>
                        <TH class=searchdisplay align=left>  Post Code  </TH>
                        <TH class=searchdisplay align=left>  Country</TH>
                        <TH class=searchdisplay align=left>  Phone No</TH>
                        <TH class=searchdisplay align=left>  SIC </TH>
                        <TH class=searchdisplay align=left>  CC Date</TH>
                        <TH class=searchdisplay align=right>Credit Rating</TH>
                        <TH class=searchdisplay align=right>Credit Limit (in GBP)</TH>

                  <%    int iCounter = 1;
                              if(request.getParameter("Navigation") != null && request.getParameter("Navigation").equals("Next"))
                                    iRecordNumber = Integer.parseInt(request.getParameter("number"));
                            } else if(request.getParameter("Navigation")!=null && request.getParameter("Navigation").equals("Previous"))
                                                      if(iRows==iRecordNumber && iRows%iRecOnPage > 0)
                                                            iRecordNumber= Integer.parseInt(request.getParameter("number"));
                              while(iRows>iRecordNumber && iCounter<(iRecOnPage+1) ) { %>
                              <% vectInner=(Vector)vectOuter.elementAt(iRecordNumber);
                                       if (strCustName.equals(vectInner.elementAt(0).toString())) {%>
                                          <% if ((iCounter%iRecOnPage) == 1) {%>
                                                      <td><%=vectInner.elementAt(0) %></td>
                                                      <td><%=vectInner.elementAt(1) %></td>       
                                                      <td><%=vectInner.elementAt(2) %></td>
                                                      <td><%=vectInner.elementAt(3) %></td>       
                                                      <td><%=vectInner.elementAt(4) %></td>
                                                      <td><%=vectInner.elementAt(5) %></td>
                                                      <td><%=vectInner.elementAt(6) %></td>
                                                      <td><%=vectInner.elementAt(7) %></td>
                                          <% } else {%>
                                          <% } %>
                                    <% } else {%>
                                                <td><%=vectInner.elementAt(0) %></td>
                                                <td><%=vectInner.elementAt(1) %></td>       
                                                <td><%=vectInner.elementAt(2) %></td>
                                                <td><%=vectInner.elementAt(3) %></td>       
                                                <td><%=vectInner.elementAt(4) %></td>
                                                <td><%=vectInner.elementAt(5) %></td>
                                                <td><%=vectInner.elementAt(6) %></td>
                                                <td><%=vectInner.elementAt(7) %></td>
                                                <% strCustName = vectInner.elementAt(0).toString(); %>
                                    <% } %>
                                    <% strCcDate = vectInner.elementAt(8).toString(); %>
                                    <td align = right><%=vectInner.elementAt(9) %></td>
                                  <td align = right><%=vectInner.elementAt(10) %></td>
                                    <% if (iRows > iRecordNumber +1)
                                                vectComparison = (Vector)vectOuter.elementAt(iRecordNumber+1);
                                                strNextCustName = vectComparison.elementAt(0).toString();
                                                strNextCustName ="";
                                          if (!strCustName.equals(strNextCustName)) {%>
                                                      <td colspan = 11 >&nbsp;</td>
                                    <% }      
                                                       strDisplay=strDisplay+"Records  "+(iRecordNumber+1);
                                                      strDisplay=strDisplay+" to  "+(iRecordNumber+1)+" of "+iRows;
                                                if ((iRecordNumber==(iRows-1))&&(iCounter!=iRecOnPage))
                                                      strDisplay=strDisplay+" to  "+(iRecordNumber+1)+" of "+iRows;
                  <% } // end of while loop %>
                  <% if(iRows > iRecordNumber) {%>
                         <a href = "Details.jsp?Navigation = Next&number=<%=iRecordNumber %>">Next</a>
                  <% } else { %>
                              <font size = 2 color = "c0c0c0">Next</font>
                  <% } %>
                  <% if(iRecordNumber > iRecOnPage) {%>
                        <a href = "Details.jsp?Navigation = Previous&number=<%=iRecordNumber %>">Previous</a>
                  <% } else { %>
                              <font size = 2 color = "c0c0c0">Previous</font>
                  <% } %>
<%} else {%>
            <h1>No Records to Display </h1>
<% } // end of if (iFlag==0) %>

The ReportBean is as follows
import java.sql.*;
import java.util.*;

public class ReportBean {
      private Connection pvt_conn;

       * method selectRecords(String argQuery)-It takes input query.
       *@return It returns Vector
       *@param argQuery Takes Query as input.

      public java.util.Vector  selectRecords(String argQuery) throws Exception
            ResultSet l_rs=null;
            ResultSetMetaData l_meta = null;
            java.util.Vector vv_rows = new java.util.Vector();
                  System.out.println("**************Before Connection**************");
                  pvt_conn = DriverManager.getConnection();
                  System.out.println("**************After Connection**************");
                  Statement l_stmt = pvt_conn.createStatement();
                  System.out.println("**************After Create Startement**************");
                  l_rs = l_stmt.executeQuery(argQuery);
                  System.out.println("*************Query Executed Properly************");
                  l_meta = l_rs.getMetaData();
                  System.out.println("*************Got Meta Data *****************");
                  int l_columnCount = l_meta.getColumnCount();
                  System.out.println("************** No of Columns ************* " + l_columnCount);
                  int m = 0;

                  while( {
                        java.util.Vector v_row = new java.util.Vector();
                        for(int n = 1 ; n <= l_columnCount ;n++) {
                        //      System.out.println("******Value of *****"+ n + "is [" + l_rs.getString(n)+ "]");
                     //System.out.println("*********** Total No of Records fetch ************" + m);
                  System.out.println("*********** out of while loop ************");
            catch(Exception e){
                  throw new Exception();
            return vv_rows;
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline


Expert Comment

ID: 6254445

I face this error when i view this page in the browser. It says


"[05/Jul/2001:13:50:36] warning (26668): JSP compilation error: java.lang.Excepti
on: JSP parse error (line 6) - USEBEAN tag is invalid, stack: java.lang.Exceptio
n: JSP parse error (line 6) - USEBEAN tag is invalid"                  

What's wrong with the bean? What is the iRows for? In your while statement you specify that the iRows must be > than the iRecordsNumber but you initiate the iRows = 0 at the beginning and it was never incremented.

Please help.

Jason (
U can email meif u wish to

Expert Comment

ID: 6256099
did you try mine?

Expert Comment

ID: 6258125

Nope, I have not try yours. But I actually manage to modified rajendra's code without using the bean and it works.


Expert Comment

ID: 6821910
Force/accepted by

Community Support Moderator
Experts Exchange


Having two accounts is a specific violation of the Membership agreement, and the fact that you abandoned a number of questions in one account and have a number of abandoned questions in the second makes the offense more egregious. You will be contacted by Admin.


Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now