Pagination with jsp Example.

Pagination Example using Servlet and Hibernate..

Step-1
reportWithPagination.jsp


    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
        pageEncoding="ISO-8859-1"%>
    <%@page import="java.util.List"%>
    <%@page import="com.nitya.syntel.*"%>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <style type="text/css">
    .pg-normal {
        color: #0000FF;
        font-weight: normal;
        text-decoration: none;
        cursor: pointer;
    }
    
    .pg-selected {
        color: #800080;
        font-weight: bold;
        text-decoration: underline;
        cursor: pointer;
    }
    </style>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Pagination Using Java Script </title>
    </head>
    
    <script type="text/javascript">
    function Pager(tableName, itemsPerPage) {
        this.tableName = tableName;
        this.itemsPerPage = itemsPerPage;
        this.currentPage = 1;
        this.pages = 0;
        this.inited = false;
        
        this.showRecords = function(from, to) {        
            var rows = document.getElementById(tableName).rows;
            // i starts from 1 to skip table header row
            for (var i = 1; i < rows.length; i++) {
                if (i < from || i > to)  
                    rows[i].style.display = 'none';
                else
                    rows[i].style.display = '';
            }
        }
        
        this.showPage = function(pageNumber) {
         if (! this.inited) {
          alert("not inited");
          return;
         }
    
            var oldPageAnchor = document.getElementById('pg'+this.currentPage);
            oldPageAnchor.className = 'pg-normal';
            
            this.currentPage = pageNumber;
            var newPageAnchor = document.getElementById('pg'+this.currentPage);
            newPageAnchor.className = 'pg-selected';
            
            var from = (pageNumber - 1) * itemsPerPage + 1;
            var to = from + itemsPerPage - 1;
            this.showRecords(from, to);
        }   
        
        this.prev = function() {
            if (this.currentPage > 1)
                this.showPage(this.currentPage - 1);
        }
        
        this.next = function() {
            if (this.currentPage < this.pages) {
                this.showPage(this.currentPage + 1);
            }
        }                        
        
        this.init = function() {
            var rows = document.getElementById(tableName).rows;
            var records = (rows.length - 1); 
            this.pages = Math.ceil(records / itemsPerPage);
            this.inited = true;
        }
    
        this.showPageNav = function(pagerName, positionId) {
         if (! this.inited) {
          alert("not inited");
          return;
         }
         var element = document.getElementById(positionId);
         
         var pagerHtml = '<span onclick="' + pagerName + '.prev();" class="pg-normal"> « Prev </span> | ';
            for (var page = 1; page <= this.pages; page++) 
                pagerHtml += '<span id="pg' + page + '" class="pg-normal" onclick="' + pagerName + '.showPage(' + page + ');">' + page + '</span> | ';
            pagerHtml += '<span onclick="'+pagerName+'.next();" class="pg-normal"> Next »</span>';            
            
            element.innerHTML = pagerHtml;
        }
    }
    </script>
    
    <body>
    
    <h1>Pagination Using Java Script</h1>
    
    <%
        List list = (List) session.getAttribute("studentDetails");
    %>
    
    <table border="1" id="results">
        <tr bgcolor="orange">
            <td><strong>Product Id</strong></td>
            <td><strong>Product Name</strong></td>
            <td><strong>price</strong></td> 
        </tr>
        <%
            for (int i = 0; i < list.size(); i++) {
        %>
        <tr>
            <%
               Product studentDetailsDTO = (Product) list
                            .get(i);
                    out.println("<td>" + studentDetailsDTO.getProductId()
                            + "</td>");
                    out.println("<td>" + studentDetailsDTO.getProName()
                            + "</td>");
                    out.println("<td>" + studentDetailsDTO.getPrice() + "</td>");
                  
            %>
        </tr>
        <%
            }
        %>
    </table>
    <div id="pageNavPosition"></div>
    
    <script type="text/javascript"><!--
            var pager = new Pager('results', 2); 
            pager.init(); 
            pager.showPageNav('pager', 'pageNavPosition'); 
            pager.showPage(1);
        //--></script>
    
    </body>
    </html>

Step2

ProductDao.Java

package com.nitya.syntel;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;

public class ProductDao {
   
    int count;
    public ArrayList<Product> getData(){

        ArrayList empList = new ArrayList();

         Product empObj;

         try {

             String connectionURL = "jdbc:oracle:thin:@localhost:1521/ORCL ";

             Connection connection = null;

             Statement statement = null;

             ResultSet rs = null;

             Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();

             connection = DriverManager.getConnection(connectionURL, "scott",
                     "tiger");

             statement = connection.createStatement();

             String QueryString = "SELECT * from products";

             rs = statement.executeQuery(QueryString);
          
             while (rs.next()) {
                
                 count++;   
                Product p=new Product();
                p.setPrice(rs.getInt("price"));
                p.setProName(rs.getString("pname"));   
                p.setProductId(rs.getInt("pid"));
                empList.add(p);
                }
        
         }
        
         catch (Exception ex) {

             System.out.println("Unable to connect to batabase." + ex);

         }
        return empList;

    }
    public int getCount()
    {
    return count;   
    }
    }

Step-3

Product.java

package com.nitya.syntel;

public class Product {
    private int productId;
    private String proName;
    private double price;

    public void setProductId(int productId)
    {
        this.productId = productId;
    }
    public int getProductId()
    {
        return productId;
    }

    public void setProName(String proName)
    {
        this.proName = proName;
    }
    public String getProName()
    {
        return proName;
    }

    public void setPrice(double price)
    {
        this.price = price;
    }
    public double getPrice()
    {
        return price;
    }

}
Step-4

Controller.java

package com.nitya.syntel;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class Controller extends HttpServlet {
    static final long serialVersionUID = 1L;

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {

       
        HttpSession httpSession = request.getSession();
        ProductDao dao = new ProductDao();
        ArrayList<Product> list = dao.getData();

        httpSession.setAttribute("studentDetails", list);
        RequestDispatcher dispatcher = request
                .getRequestDispatcher("reportWithPagination.jsp");
        dispatcher.forward(request, response);

    }
}
Step-5

index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Pager Example - www.javaworkspace.com</title>
</head>
<body>
<h1>PagerTag Example - <a href="http://www.javaworkspace.com"
    target="_blank">www.google.com</a></h1>
<form method="post" action="Controller"><input type="submit"
    value="Get Report"></form>
</body>
</html>

Step-6
web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">

    <display-name>Pager Tag</display-name>

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

    <servlet>
      
        <display-name>Controller</display-name>
        <servlet-name>Controller</servlet-name>
        <servlet-class>
            com.nitya.syntel.Controller
        </servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>Controller</servlet-name>
        <url-pattern>/Controller</url-pattern>
    </servlet-mapping>

</web-app>



List of jar file to be added in lib folder....
  • pager-taglib-2.0.jar.
  • ojdbc14.jar.
  • servlet-api-2.5.jar
And the screenshot of the above is...
 





Add all hibernate and servlet dependancy jar.........

13 comments:

  1. Hi Nityananda sir,

    Thank you for such a nyc example...
    it is working excellent and it helped lot in understanding pagination.

    Regards,
    Rinnie

    ReplyDelete
  2. Hi Nityananda sir,

    Thank you for such a nice example.
    it is working excellent and it helped lot in understanding pagination.

    Regards,
    Narasimhulu

    ReplyDelete
  3. Your blog has excellent information On JSP.

    ReplyDelete
  4. Hi Nitya
    Thank you very much for such a excellent example.it is working fine

    ReplyDelete

  5. Given so much info in it, These type of articles keeps the users interest in the website, and keep on sharing more ... good luck. java training institutes in chennai | java j2ee training institutes in velachery

    ReplyDelete
  6. How would i hide the page numbers? i would want to do is to see previous and next only.

    ReplyDelete