上课老师讲解了jsp分页 ,关于计算总页数
他的算法是 totalPage=(totalRecords+pageSize-1)/pageSize; 他说如果不好理解,就用 i f else 判断。
下课看书
偶然想起了以前,的一个算法
totalPage=(totalRecords%pageSize==0)? (totalRecords/pageSize): ((totalRecords/pageSize)+1);
感觉 下面的一个好理解点 ............呵呵 ,如果总记录数除以 每一页的记录数就取 总页数totalRecords/pageSize ,否则取 ((totalRecords/pageSize)+1。
代码:
<%@ page contentType="text/html; charset=gb2312" language="java" import="java.sql.*" errorPage="" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无标题文档</title>
</head>
<body>
<%
int currentPage=1;
int totalPage=1;
int pageSize=20;
int totalRecords=0;
String page1=request.getParameter("page");
if(page1==null||page1.equals(""))
{
currentPage=1;
}
else
{
currentPage =Integer.parseInt(page1);
}
// 郁闷 !!! 开始的时候,连接老是出错,唉, 现在不配置数据源了 说缺少驱动。,直接这样成功//了。
String sql="select count(*) from stu";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:driver={Microsoft Access Driver (*.mdb)};DBQ=c://test.mdb");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery(sql);
rs.next();
totalRecords=rs.getInt(1);
//totalPage=(totalRecords+pageSize-1)/pageSize;
totalPage=(totalRecords%pageSize==0)? (totalRecords/pageSize): ((totalRecords/pageSize)+1);
String name;
String age;
String school;
sql="select * from stu" ;
rs=stmt.executeQuery(sql);
for(int i=0;i<=(currentPage-1)*pageSize;i++) {rs.next(); } // 先跳过(curPage-1)*pageSize
%>
<center>
<table border="1" width="80%">
<tr>
<td>姓名</td>
<td>年龄</td>
<td>学校</td>
</tr>
<%
for(int k=1;k<=pageSize;k++){
rs.next();
name=rs.getString(2);
age=rs.getString(3);
school=rs.getString(4);
%>
<tr>
<td><%=name%></td>
<td><%=age%></td>
<td><%=school%></td>
</tr>
<%
}
%>
</table>
</center>
</body>
</html>