简单实现网页信息分页显示

<%!
int toptalPageCount=0; //信息总页数
int pageSize = 5; //页面大小,即每页显示的记录数
int totalCount; //信息的总条数
int index=0;
Connection con = null;
PreparedStatement ps=null;
ResultSet rs =null;
//给toptalPageCount赋值,算出一共多少页
void setTotalCount(int totalCount){
toptalPageCount = this.totalCount%pageSize ==0?(this.totalCount/pageSize):(this.totalCount/pageSize+1);
}
%>


<%
//传递页码跳转的值
if(request.getParameter("index") != null){
index =Integer.parseInt(request.getParameter("index"));
}

//连接数据库
Context ctx = new InitialContext();
DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/news");


try{

//查询一共多少条信息
con = ds.getConnection();
ps = con.prepareStatement("select count(1) from news");
rs = ps.executeQuery();
//给totalCount赋值
if(rs.next()){
totalCount =Integer.parseInt(rs.getString("count(1)"));
}

//判断上一页,下一页
if(index <=0){
index =1;
}else if(index >=12){
index =12;
}

//执行分页查询
ps = con.prepareStatement("select ntitle from news limit ?,?");
ps.setInt(1, (index-1)*pageSize);
ps.setInt(2, pageSize);
rs = ps.executeQuery();
//读取新闻数据
while(rs.next()){
out.print(rs.getString("ntitle")+"<br>");
}

//传递totalCount参数
setTotalCount(totalCount);

out.print("<a href='index.jsp?index="+(index-1)+"'>"+"上一页"+"</a>");

//显示页码 
for(int i=0; i<toptalPageCount;i++){
out.print("<a href='index.jsp?index="+(i+1)+"'>"+(i+1)+"</a>&nbsp;");
}
out.print("<a href='index.jsp?index="+(index+1)+"'>"+"下一页"+"</a>");
}catch(Exception e){
e.printStackTrace();
}finally{

//释放资源
try{
rs.close();
}catch(Exception e){
e.printStackTrace();
}
try{
ps.close();
}catch(Exception e){
e.printStackTrace();
}
try{
con.close();

}catch(Exception e){
e.printStackTrace();
}
}
%>

转载于:https://www.cnblogs.com/Citrus-lzx/p/8277595.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值