Share on Google+Share on Google+

What's wrong with my pagination code in JSP?
2 Answer(s)      4 years and 10 months ago
Posted in : Java Beginners

Dear experts,

I've tried the following codes which I have copied from Java Ranch forum and deleted whatever lines that NetBean IDE has given me error signal.

The resulted page is that it can display all 10 records but I only want 5 records to be shown.

Hope someone can advise me how to.


 print("code sample");

<%@ page language="java" contentType="text/html; charset=UTF-8"
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
<[email protected] language="java" import ="java.sql.*" %>
            String access = (String) session.getAttribute("access");
            if (access == null) {
<%-- Display page --%>
<%          Connection conn = null;
            PreparedStatement ps = null;
            ResultSet rs = null;
            Statement stmt = null;

            boolean isPageSelected = false;
            int lb = 0, ub = 0, pg = 0, totalrecords = 0, recordsPerPage = 5;
            // variables used in paging

            String selected_page = request.getParameter("page");
            if (selected_page == null || selected_page == "" || selected_page.equals("")) {// page not selected
               // isPageSelected = false;
              //  selected_page = "";
              //  lb = 0;
              //  ub = recordsPerPage;
           // } else {// page is selected
                isPageSelected = true;
               // pg = Integer.valueOf(selected_page).intValue();
                 pg = Integer.valueOf(2).intValue();
                lb = recordsPerPage * (pg - 1);
                ub = lb + recordsPerPage;
            try {
                String url = "jdbc:odbc:ODBC1";
                conn = DriverManager.getConnection(url);
                stmt = conn.createStatement();
            } catch (Exception e) {
            String query = "select * from students";

            rs = stmt.executeQuery(query);
            //rs.last(); // Jump to last row
            totalrecords = rs.getRow(); // get the row count
          //  rs.beforeFirst();
            // reset to allow forward cursor processing

            int noofpages = 0;
            if (totalrecords % recordsPerPage == 0) {
                noofpages = totalrecords / recordsPerPage;
            } else {
                noofpages = totalrecords / recordsPerPage + 1;

            int cnt = lb;
            //lb + 1; // move to record
              while ( {
                                int id = rs.getInt("ID");      
                    <td><%=rs.getString("studentName")%> </td>
                    <td><%=rs.getString("fatherName")%> </td>
                    <td><%=rs.getInt("age")%> </td>
                    <td><%=rs.getString("country")%> </td></tr>


        <link rel="stylesheet" style type ="text/css" href ="style.css">
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <div id="header">Welcome to CARE counselling</div>
        <div id="center" class="column">
            <h5>Members Record</h5>
            <table border ="1" cellspacing="0" cellspacing="0" align="center" class="bordered">
                <tr><td><b>Student Name</b></td>
                    <td><b>Father Name</b></td>

                   </tr> <%}

                <td>Total Number of Members: <%=noofpages - 1%>
                    <br />
                    To return to login page : "<a href="login.jsp">Click here</a>"</td>
            <br />
            <br />


    print("code sample");


View Answers

May 25, 2012 at 3:16 PM

JSP Pagination

The given code retrieves 5 records per page from database. Here db22admin is our database. Named the given file 'pagination.jsp'.

<%@ page import="java.sql.*" %>
public int nullIntconvert(String str){
int num=0;
else if((str.trim()).equals("null")){
else if(str.equals("")) {
catch(Exception e){ }
return num;
Connectionconn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db2admin","root", "root");
 int showRows=5;
int totalRecords=5;
int totalRows=nullIntconvert(request.getParameter("totalRows"));
int totalPages=nullIntconvert(request.getParameter("totalPages"));
int iPageNo=nullIntconvert(request.getParameter("iPageNo"));
int cPageNo=nullIntconvert(request.getParameter("cPageNo"));
int startResult=0;
int endResult=0;
String query1="SELECT SQL_CALC_FOUND_ROWS * FROM db2admin.reg limit "+iPageNo+","+showRows+"";
PreparedStatement ps1=conn.prepareStatement(query1);
ResultSet rs1=ps1.executeQuery();

String query2="SELECT FOUND_ROWS() as cnt";
PreparedStatement ps2=conn.prepareStatement(query2);
ResultSet rs2=ps2.executeQuery();
<html><h3>Pagination of JSP page</h3>
<input type="hidden" name="iPageNo" value="<%=iPageNo%>">
<input type="hidden" name="cPageNo" value="<%=cPageNo%>">
<input type="hidden" name="showRows" value="<%=showRows%>">
<table width="100%" cellpadding="0" cellspacing="0" border="1" >
catch(Exception e){
<tr><td colspan="3">
int i=0;
int cPage=0;
int prePageNo=(cPage*totalRecords)-((totalRecords-1)+totalRecords);
<a href="paging.jsp?iPageNo=<%=prePageNo%>&cPageNo=<%=prePageNo%>">Previous</a>
<a href="paging.jsp?iPageNo=<%=i%>" style="cursor:pointer;color: red"><b><%=i%></b></a>
else if(i<=totalPages){
<a href="paging.jsp?iPageNo=<%=i%>"><%=i%></a>
if(totalPages>totalRecords && i<totalPages){
<a href="paging.jsp?iPageNo=<%=i%>&cPageNo=<%=i%>">Next</a>
<b>Rows <%=startResult%> - <%=endResult%> Total Rows <%=totalRows%> </b>

May 28, 2012 at 3:59 PM


Thanks for posting the above code.

I have a problem here.

As I'm using MsAccess, I still couldn't figure out the code for the String query.

I have tried the following queries but it's not working :

String query1 = "SELECT * FROM students" + iPageNo + "," + showRows + "";

String query1 = "SELECT * FROM students LIMIT 0,5" + iPageNo + "," + showRows + "";

String query1 = "SELECT * FROM (SELECT top " + showRows+" * FROM (SELECT top 12 id, studentName, fatherName, age, country from students))";

But, none is working out.

Hope you can tell me what's the query to use.

Many thanks.

Java Spring Hibernate Struts Training What does core Java include? java What are some way to learn Java quickly? Is it required to learn Java before learning Java Script? Is it necessary to learn java script before learning PHP? Are HTML5 and Java Script boosts Java career? Is Java object oriented? Fingerprint application with Java Uninstall Oracle Virtual Box JSON to HashMap Free Java online Training I want example of Control Statement in Java ANSI Color Codes with Python Create a Program that Calculates Input What is difference between JDK,JRE and JVM? How to see ubuntu version on server? How to get Page Source in Selenium (WebDriver) using Java? The path to the driver executable must be set by the webdriver.gecko.driver system property parse data from a link in java Java Program Qns using BlueJ How to fix HAX Kernel Module Is Not Installed error? Installing Audacity Looking for code Logic to check track changes & Coments in MSWord, MSWordx, MSExcel, MSExcelx is ON/OFF Installing JDK on Mac SAX Parser exception ERROR 601 (42P00): Syntax error. Encountered Thread java.lang.NoClassDefFoundError: org/apache/commons/fileupload/FileItemFactory How to install Ubuntu 16.04 LTS? HttpServletRequest cannot be resolved to a type in eclipse - Solved Unhandled event loop exception GC overhead limit exceeded Spring Data jpa with apache phoenix Caused by: java.lang.IllegalArgumentException: Not a host:port pair: PBUF o.a.h.h.z.RecoverableZooKeeper - Possibly transient ZooKeeper, quorum= com.thinkaurelius.titan.diskstorage.hbase.HBaseStoreManager class not found com.thinkaurelius.titan.diskstorage.hbase.HBaseStoreManager not found How to download and install Java 8 on Windows? How to uninstall JDK 7? How to install gtk-doc-tools package in Ubuntu? How to install Oracle JDK 8 on Ubuntu? ejabberd_ctl.beam not found - Solved How to convert date to UTC format in Java? How to install autoconf, automake and libtool in Ubuntu 15.10? How to convert current date to mm dd yyyy format in Java? How to convert current date to dd mm yyyy format in Java? How to stop window closing in "internalFrameClosing" event. How to find list of all index in Neo4j? file location SASLError using PLAIN: not-authorized how to convert war file into .exe file using java code


Advertisement null