We can create pagination example in JSP easily. It is required if you have to display many records. Displaying many records in a single page may take time, so it is better to break the page into parts. To do so, we create pagination application.

In this pagination example, we are using MySQL database to fetch records.

We have created “emp” table in “test” database. The emp table has three fields: id, name and salary. Either create table and insert records manually or import our sql file.

index.jsp

view.jsp

<%@ page import="java.util.*,com.javatpoint.dao.*,com.javatpoint.beans.*" %>  
<%  
String spageid=request.getParameter("page");  
int pageid=Integer.parseInt(spageid);  
int total=5;  
if(pageid==1){}  
else{  
    pageid=pageid-1;  
    pageid=pageid*total+1;  
}  
List list=EmpDao.getRecords(pageid,total);  
  
out.print("

Page No: “+spageid+”

“); out.print(”

“); out.print(“”); for(Emp e:list){ out.print(”  “); } out.print(”

Id Name Salary
“+e.getId()+” “+e.getName()+” “+e.getSalary()+”

“); %> 1 2 3

Emp.java

package com.javatpoint.beans;  
  
public class Emp {  
private int id;  
private String name;  
private float salary;  
//getters and setters  
}

EmpDao.java

package com.javatpoint.dao;  
import com.javatpoint.beans.*;  
import java.sql.*;  
import java.util.ArrayList;  
import java.util.List;  
public class EmpDao {  
  
    public static Connection getConnection(){  
        Connection con=null;  
        try{  
            Class.forName("com.mysql.jdbc.Driver");  
            con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","","");  
        }catch(Exception e){System.out.println(e);}  
        return con;  
    }  
  
    public static List getRecords(int start,int total){  
        List list=new ArrayList();  
        try{  
            Connection con=getConnection();  
            PreparedStatement ps=con.prepareStatement(  
"select * from emp limit "+(start-1)+","+total);  
            ResultSet rs=ps.executeQuery();  
            while(rs.next()){  
                Emp e=new Emp();  
                e.setId(rs.getInt(1));  
                e.setName(rs.getString(2));  
                e.setSalary(rs.getFloat(3));  
                list.add(e);  
            }  
            con.close();  
        }catch(Exception e){System.out.println(e);}  
        return list;  
    }  
}

Output

JSP Pagination Example 1 JSP Pagination Example 2 JSP Pagination Example 3 JSP Pagination Example 4