【原创】jsp 实现分页功能
程序代码:
<%@ page contentType="text/html" pageEncoding="utf-8" language="java"%> <%@ page import="java.sql.*"%> <html> <head> <title>hello</title> </head> <body> <table border="1" bgcolor="#FF051"> <thead> <th>id</th> <th>姓名</th> <th>性别</th> <th>年龄</th> <th>电话</th> <th>地址</th> </thead> <tbody> <%! public static final String driver= "com.mysql.jdbc.Driver"; public static final String user= "[Username]"; public static final String password= "[Password]"; public static final String url= "jdbc:mysql://localhost:3306/[DataBaseName]"; public static final int PAGESIZE = 3; //控制分页数 int pageCount; //控制每页显示的数据数量 int curPage = 1; //当前页面的页数 %> <% //一页放5个 try{ Class.forName(driver); Connection con = DriverManager.getConnection(url,user,password); String sql = "select * from [tableName]"; PreparedStatement stat = con.prepareStatement(sql,ResultSet.TYPE_FORWARD_ONLY,ResultSet.CONCUR_READ_ONLY); ResultSet rs = stat.executeQuery(); rs.last(); int size = rs.getRow(); pageCount = (size%PAGESIZE==0)?(size/PAGESIZE):(size/PAGESIZE+1); String temp = request.getParameter("curPage"); if(temp==null){ temp="1"; } curPage = Integer.parseInt(temp); if(curPage>=pageCount) curPage = pageCount; if(curPage<=0){ curPage=1; out.print("已经是第一页了"); } boolean flag = rs.absolute((curPage-1)*PAGESIZE+1); int count = 0; do{ if(count>=PAGESIZE)break; String uno = rs.getString(1); String username = rs.getString(2); String gender = rs.getString(3); int age = rs.getInt(4); String phone = rs.getString(5); String address = rs.getString(6); count++; %> <tr> <td><%=uno%></td> <td><%=username%></td> <td><%=gender%></td> <td><%=age%></td> <td><%=phone%></td> <td><%=address%></td> </tr> <% }while(rs.next()); con.close(); } catch(Exception e){ } %> </tbody> </table> <a href = "index.jsp?curPage=1" >首页</a> <a href = "index.jsp?curPage=<%=curPage-1%>" >上一页</a> <a href = "index.jsp?curPage=<%=curPage+1%>" >下一页</a> <a href = "index.jsp?curPage=<%=pageCount%>" >尾页</a> 第<%=curPage%>页/共<%=pageCount%>页 </body> </html>