We can create pagination instances in JSP easily. It is needed when you have to show a lot of data. Displaying a lot of data in a single web page may also take time, so it's miles better to interrupt the web page into parts. To do so, we create a pagination application.
In this pagination instance, we use the MySQL database to fetch data.
We have created an "emp" table in "test" database. The emp table has three fields: id, and salary. Either create a table and insert data manually or import our square file.
<a href="view.jsp?page=1">View Employees</a>
view.jsp
<%@ page import="java.util.*,com.intellinuts.dao.*,com.intellinuts.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<Emp> list=EmpDao.getRecords(pageid,total); out.print("<h1>Page No: "+spageid+"</h1>"); out.print("<table border='1' cellpadding='4' width='60%'>"); out.print("<tr><th>Id</th><th>Name</th><th>Salary</th>"); for(Emp e:list){ out.print("<tr><td>"+e.getId()+"</td><td>"+e.getName()+"</td> <td>"+e.getSalary()+"</td></tr>"); } out.print("</table>"); %> <a href="view.jsp?page=1">1</a> <a href="view.jsp?page=2">2</a> <a href="view.jsp?page=3">3</a>
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.intellinuts.dao; import com.intellinuts.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<Emp> getRecords(int start,int total){ List<Emp> list=new ArrayList<Emp>(); 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; } }
Download this example (Developed in Eclipse)
Output