Paging a JSP page source code -required URGENT-

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!
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

//    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){
// 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));
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.
Cloud Class® Course: MCSA MCSE Windows Server 2012

This course teaches how to install and configure Windows Server 2012 R2.  It is the first step on your path to becoming a Microsoft Certified Solutions Expert (MCSE).

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;

Experts Exchange Solution brought to you by ConnectWise

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial

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
did you try mine?

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

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.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.