分页实现(jsp版)
作者:
∣来源:
BlogJava∣
原文地址∣
2006-2-26
<%
@ page contentType
=
"
text/html;charset=GB2312
"
%>
<%
@ page
import
=
"
java.sql.*
"
%>
<
html
>
<
title
>
分页显示(jsp版)
</
title
>
<
body
>

<%!
int
pageSize
=
5
;
//
每页显示的记录数
int
pageCount
=
0
;
//
总页数
%>

<%
Connection con;
String DatabaseDriver
=
"
com.microsoft.jdbc.sqlserver.SQLServerDriver
"
;
String CnnStr
=
"
jdbc:microsoft:sqlserver://127.0.0.1:1433;databasename=Shopping
"
;

try
{
Class.forName(DatabaseDriver);
con = DriverManager.getConnection(CnnStr, "sa", "11");
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);//可滚动查询数据的结果集
ResultSet rs = stmt.executeQuery("select * from ProductInfo order by P_ID");
rs.last(); //让游标到表中的最后一行
int rowCount = rs.getRow(); //获取记录总数.
//out.print("总记录数为"+rowCount);
//总页数的计算公式
pageCount = (rowCount % pageSize == 0) ? (rowCount / pageSize ) : (rowCount / pageSize +1);
int showPage = 1;//当前页
%>



<%
//取得用户所指定的页
String goToPage = request.getParameter("showPage");

if (goToPage == null)
{
goToPage = "1";
}
//转换成整形

try
{
showPage = Integer.parseInt(goToPage);
}

catch (NumberFormatException ex)
{
showPage = 1;
}
//当前页小于等于第一页 则按第一页算 如果 当前页大于等于总页数则为最后页

if(showPage <=1)
{
showPage = 1;
}

else if(showPage >= pageCount)
{
showPage = pageCount;
}
//游标的位置 (当前页 - 1) * 页面大小 + 1
int posion = (showPage -1 ) * pageSize + 1;
//设置游标的位置
rs.absolute(posion);

%>


<table border="1" cellspacing="0" cellpadding="0">
<tr>
<th>商品号</th>
<th>商品名称</th>
</tr>
<%
int i =0;
//循环显示表中的数据 pageSize(每页所显示的记录)
//rs.isAfterLast() 游标是否在最后一行之后 说明后面已经没记录

while(i<pageSize && !rs.isAfterLast())
{
%>
<tr>
<td><%=rs.getString(1)%></td>
<td><%=rs.getString(2)%></td>
</tr>
<%rs.next();i++;}%>
</table>


<table width="624">
<form action="" method="get">

<tr>
<td>

<%if(showPage < pageCount)
{%>
<a href="Noname1.jsp?showPage=<%=showPage+1%>">[下一页]</a>
<%}%>
</td>

<td><%if(showPage > 1)
{%>
<a href="Noname1.jsp?showPage=<%=showPage-1%>">[上一页]</a>
<%}%>
</td>

<td> 共<%=pageCount%>页 </td>
<td> 第<%=showPage%>页 </td>
<td> <a href="Noname1.jsp?showPage=1">『首页』</a> </td>
<td> <a href="Noname1.jsp?showPage=<%=pageCount%>">『尾页』</a> </td>
<td> <%=rowCount%> </td>
<td>
转到<input type="text" name="showPage" size="4"></input>
<input type="submit" name="go" value="提交"></input>
</td>
</tr>
</form>
</table>
<%
con.close();

}
catch
(ClassNotFoundException e1)
{out.print(e1.getMessage());}

catch
(SQLException e2)
{ out.print(e2.getMessage());}
%>
</
body
>
</
html
>





































































































































