JSP+JDBC_假分页 2008-08-10 15:00
假分页:将数据全部读取出来,放入ResultSet中,再分别显示,图示如下:
<%@ page contentType="text/html;charset=gb2312"%>
<%@ page import="java.sql.*"%>
<html>
<head>
<title></title>
</head>
<body>
<center>
<h1>
人员列表
</h1>
<hr>
<br>
<%!
final String jspUrl="index_false_1.jsp";
%>
<%
//定义如下分页变量
//1.定义每页要显示的页数
int lineSize = 3;
//2.定义一个当前是第几页
int currentPage = 1;
// 计算出总页数
int pageSize= 0;
// 总记录数
int allRecorders=0;
// 接收传过来的当前页,第一次打开时没有传过来的值会发生异常,因此要try{}catch{}
try{
currentPage = Integer.parseInt(request.getParameter("cp"));
}catch(Exception e){
}
final String DBDRIVER = "org.gjt.mm.mysql.Driver";
final String DBURL = "jdbc:mysql://59.64.167.41:3306/ren";
final String DBUSER = "root";
final String DBPASSWORD = "111111";
Connection conn = null;
%>
<%
try {
Class.forName(DBDRIVER);
conn = DriverManager.getConnection(DBURL, DBUSER, DBPASSWORD);
PreparedStatement pstmt = null;
//先求出记录总数
String sql = "select count(Id) from person";
pstmt = conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
if(rs .next())
{
allRecorders = Integer.parseInt(rs.getString(1));
pageSize = (allRecorders+lineSize-1)/lineSize;
}
rs.close();
pstmt.close();
sql = "select Id,Name,Password from person";
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
%>
<script language="javascript" >
function openPage(curPage)
{
document.spage.cp.value = curPage;
document.spage.submit();
}
function selOpenPage()
{
document.spage.cp.value = document.spage.selectPage.value ;
document.spage.submit();
}
</script>
<form action="<%=jspUrl%>" name="spage">
总记录数:<%=allRecorders %> 共有页数:<%=pageSize %>当前页:<%=currentPage %>跳转到
<select name="selectPage" onchange="selOpenPage()">
<%
for (int i=1;i<=pageSize;i++)
{
%>
<option value="<%=i %>" <%=currentPage==i?"selected":"" %>><%=i %></option>
<%
}
%>
</select>页
<br>
<input type="button" value="首页" onclick="openPage(1)" <%=currentPage==1?"disabled" :""%>>
<input type="button" value="上一页" onclick="openPage(<%=currentPage-1 %>)" <%=currentPage==1?"disabled" :""%>>
<input type="button" value="下一页" onclick="openPage(<%=currentPage+1 %>)" <%=currentPage==pageSize?"disabled" :""%>>
<input type="button" value="尾页" onclick="openPage(<%=pageSize %>)" <%=currentPage==pageSize?"disabled" :""%>>
<input type="hidden" value="" name="cp">
</form>
<table border="1" width="80">
<tr>
<td>
编号
</td>
<td>
登陆名
</td>
<td>
密码
</td>
<td cols="2">
操作
</td>
</tr>
<%
int i = 0;
//对于输出代码之前要求按显示的页数空出
for (int j = 0; j < (currentPage - 1) * lineSize; j++) {
rs.next();
}
for (int j = 0; j < lineSize; j++) {
if (rs.next()) {
i++;
String id = rs.getString(1);
String name = rs.getString(2);
String password = rs.getString(3);
%>
<tr>
<td>
<%=id%>
</td>
<td>
<%=name%>
</td>
<td>
<%=password%>
</td>
<td>
更新
</td>
<td>
删除
</td>
</tr>
<%
}
}
rs.close();
pstmt.close();
if (i == 0) {
%>
<tr>
<td colspan="6">
没有任何数据
</td>
</tr>
<%
}
%>
</table>
<%
} catch (Exception e) {
%>
<h2>
系统出错
</h2>
<%
} finally {
conn.close();
}
%>
</center>
</body>
</html>