自己分页,下一篇会介绍使用diasplaytag组件。
使用mysql5, 有个数据表user,字段有id, username, password。
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <%@ page import="java.sql.*"%> <!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=utf-8"> <title>分页测试</title> </head> <% String driver = "com.mysql.jdbc.Driver"; String username = "root"; String password = "leng"; String url = "jdbc:mysql://localhost/test"; Connection conn = null; Statement stmt = null; ResultSet rs = null; Class.forName(driver); conn = DriverManager.getConnection(url, username, password); stmt = conn.createStatement(); String sql = "select * from user order by id asc"; rs = stmt.executeQuery(sql); %> <% int countRecord = 0; //总记录数 int pageSize = 4; // 每页记录数 int countPage = 0 ; // 总页数 int dipage = 1; // 当前页码,默认从1开始 String pages = request.getParameter("page"); if(pages == null ){ pages = "1"; } dipage = Integer.parseInt(pages); rs.last(); countRecord = rs.getRow(); if(countRecord % pageSize == 0){ countPage = countRecord / pageSize; } else { countPage = countRecord / pageSize + 1; } if((dipage-1)*pageSize == 0){ // 第一页 rs.beforeFirst(); } else { rs.absolute((dipage-1)*pageSize); } %> <body> <center> <h3>分页测试</h3> <table border="1"> <tr> <th width="100">id</th> <th width="300">用户名</th> <th width="300">密码</th> </tr> <% // 控制每页显示数 int i = 0; while(rs.next()){ %> <tr> <td><%=rs.getInt("id") %></td> <td><%=rs.getString("username") %></td> <td><%=rs.getString("password") %></td> </tr> <% i++; // 当页已显示完每页记录数,退出循环 if(i>=pageSize){ break; } } %> <tr > <td colspan="3"> <%=countRecord %>条记录,共<%=countPage %>页,当前第<%=dipage %>页,每页显示<%=pageSize %>条记录, <% if(dipage ==1) { %> <a>上一页</a> | <% }else{ %> <a href="pages.jsp?page=<%=dipage-1 %>">上一页</a> | <%} %> <% if(dipage== countPage) {%> <a>下一页</a> <%}else{ %> <a href="pages.jsp?page=<%=dipage+1 %>">下一页</a> <%} %> </td> </tr> </table> </center> <% rs.close(); stmt.close(); conn.close(); %> </body> </html>
运行效果