JavaWeb.09.新闻之分页功能

一、分页

在实现分页功能之前,咱们可以先将主页(index.jsp)表单中的method=“post” 改为method=“get”,方便之后代码的操作,同时还要注释掉破碎重组的相关代码
优势:
能显示多条信息
减少一定的麻烦

分页操作:

page:当前页数 1

rows:当前显示条数 5

举例:

–【page:1,row:5】1-5

–【page:2,row:5】6-10

–【page:3,row:5】11-15

–【page:4,row:5】…

所以规律应该为:

开始位置 begin:1+(页数-1)*条数

结束位置 end:页数*条数

分页的具体做法:

  1. 确定每页显示数据的数量
  2. 计算页数
  3. 编写SQL语句

二、实现数据分页

举例:对于新闻项目,在首页实现数据的分页,让数据显示和进行模糊查询
1.数据库:首先在数据库需要插入多条数据,方便后期分页时查看数据
2.Eclipse:
NewsDao.java

package dao;
 
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
 
import com.zking.util.DBHelper;
 
import pojo.News;
 
public class NewsDao {
	private Connection con;
	private PreparedStatement ps;
	private ResultSet rs;
	
	public List<News> queryByName(String newName,int page/*页数*/) {
		//int page=1;//页数
		int rows=5;//条数
		int begin=1+((page-1)*rows);//开始位置
		int end=page*rows;//结束位置
		
		List<News> list=new ArrayList<News>();
		try {
			con=DBHelper.getCon();
			ps=con.prepareStatement("select * from ("
					+ "select a.*,ROWNUM myr from t_news02 a where news_title like ?"
					+ ")b where myr between ? and ? ");
			ps.setString(1, "%" + newName + "%");
			ps.setInt(2, begin);
			ps.setInt(3, end);
			rs=ps.executeQuery();
			while(rs.next()) {
				News news=new News();
				//给新闻对象赋值
				news.setNewsId(rs.getInt(1));
				news.setNewsTitle(rs.getString(2));
				news.setNewsTopic(rs.getInt(3));
				news.setNewsAuthor(rs.getString(4));
				news.setNewsPublisher(rs.getString(5));
				news.setNewsContent(rs.getString(6));
				news.setNewsCount(rs.getInt(7));
				news.setNewsMarker(rs.getInt(8));
				//将新闻对象添加到集合中
				list.add(news);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			DBHelper.close(con, ps, rs);
		}
		return list;
	}
 
 
 
//怎么知道当前有几页
 
//数据库数量 / 条数
public int queryCount(String newName) {
	//int page=1;//页数
	int rows=5;//条数
	int count=0;//数据库中数据的数量
 
	try {
		con=DBHelper.getCon();
		ps=con.prepareStatement("select count(1) from t_news02 where news_title like ?");
		
		ps.setString(1, "%" + newName + "%");
		rs=ps.executeQuery();
		if(rs.next()) {
			 count=rs.getInt(1);
		}
		//返回页数 13.0/5 =2.x->3.0
	//	return Integer.parseInt(Math.ceil(count*1.0/rows)+"");
		return new Double(Math.ceil(count*1.0/rows)).intValue();
	} catch (Exception e) {
		e.printStackTrace();
	}finally {
		DBHelper.close(con, ps, rs);
	}
	return 0;
}
 
}
 

index.jsp

<%@page import="dao.NewsDao"%>
<%@page import="pojo.News"%>
<%@page import="java.nio.charset.StandardCharsets"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.PreparedStatement"%>
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.Connection"%>
<%@page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="zh">
 
<head>
    <meta charset="UTF-8">
    <title>bootstrap</title>
    <meta content="width=device-width, initial-scale=1" name="viewport">
    <link href="/web04/bootstrap-3.3.7-dist/css/bootstrap.css" rel="stylesheet">
    <script src="/web04/bootstrap-3.3.7-dist/js/jquery-3.5.1.js"></script>
    <script src="/web04/bootstrap-3.3.7-dist/js/bootstrap.js"></script>
    <style>
        * {
            outline: none !important;
        }
 
        body,
        html {
            background: #7f8d90;
        }
 
        nav,
        .breadcrumb {
            border-radius: 0px !important;
            margin-bottom: 0px !important;
        }
 
        .breadcrumb {
            margin-bottom: 20px !important;
            background: #36485c;
            color: white;
        }
 
        li h4 {
            width: 300px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
 
        .breadcrumb .active {
            color: yellow;
        }
    </style>
</head>
 
 
<body>
<%--inclide 包含 --%>
<%@include file="top.jsp" %>
 
 
 
<ol class="breadcrumb">
    <li>您当前的位置是</li>
    <li>新闻发布系统</li>
    <li class="active">首页</li>
</ol>
 
<%
//点击了表单之后 跳转的是当前这个页面 同时携带一个newName过来(查询的关键字)
	String newName=request.getParameter("newName");
	if(newName==null){
		newName="";//查询全部
	}
	
	//破碎重组【增高】(字符串变成字节数组,再把字节数组重新变成字符串)手动指定编码
//	new String(newName.getBytes(StandardCharsets.ISO_8859_1),StandardCharsets.UTF_8);
//	newName=new String(newName.getBytes(StandardCharsets.ISO_8859_1),StandardCharsets.UTF_8);
	
%>
 
<form action="${pageContext.request.contextPath}/news/index.jsp" class="form-inline" style="margin: 0px auto 20px;" method="get">
    <div class="form-group" style="display: block;text-align: center;">
        <div class="input-group">
            <div class="input-group-addon">新闻标题</div>
            <input name="newName" value="newName" class="form-control" placeholder="请在此输入搜索的关键字" type="text">
            <span class="input-group-btn">
                    <button class="btn btn-primary" type="submit">搜索🔍</button>
                </span>
        </div>
    </div>
</form>
 
<div class="container">
	<ul class="list-group">
	<%
	//设定 当前用户进行分页的名字叫做page
	String index=request.getParameter("page");
	int n=1;//默认页数第一页
	if(index!=null){
		n=Integer.parseInt(index);//设置为你携带的页数
	}
	
	//关于method=“post”会乱码
	request.setCharacterEncoding("utf-8");
	
	//查询当前数据的对应页数
	int maxPage=new NewsDao().queryCount(newName);
 
	//根据页数查询数据
	for(News news:new NewsDao().queryByName(newName,n)){
		
		
			
	%>
	
    
        <li class="list-group-item">
            <h4 class="list-group-item-heading">
            <!--  newId=1-->
                <a href=
                "${pageContext.request.contextPath}/news/read.jsp?newId=<%=news.getNewsId()%>" 
                data-placement="bottom" data-toggle="tooltip" href="" title="<%=news.getNewsTitle()%>">
                    <%=news.getNewsTitle() %>
                </a>
            </h4>
            <p class="list-group-item-text text-right">
                <span class="glyphicon glyphicon-user"><code><%=news.getNewsAuthor() %></code></span>
                <span class="glyphicon glyphicon-eye-open"><code><%=news.getNewsCount() %></code></span>
                <span class="glyphicon glyphicon-tag"><code><%=news.getNewsMarker() %></code></span>
                <span class="glyphicon glyphicon-time"><code><%=news.getNewsPublisher()%></code></span>
            </p>
        </li>
		<%
			}
		
		
		%>
		
		
    </ul>
</div>
<div class="container text-center">
    <ul class="pagination" style="margin: 20px auto;">
        <li>
          <a href="index.jsp?page=<%=Math.max(n-1,1)%>&newName=<%=newName%>"><span>&laquo;</span></a></li>
      
      	<%
      	//根据最大页码	动态生成
      		for(int i=1;i<=maxPage;i++){
      			
      		
      	%>
        <li class="<%=i==n?"active":""%>"><a href="index.jsp?page=<%=i%>&newName=<%=newName%>"><%=i %></a></li>
        <%
      			  }
        %>
    
        <li>
            <a href="index.jsp?page=<%=Math.min(n+1,maxPage)%>&newName=<%=newName%>"><span>&raquo;</span></a>
        </li>
    </ul>
</div>
<script>
$(function () {
    $('[data-toggle="tooltip"]').tooltip({
        trigger: "hover"
    })
})
</script>
</body>
</html>
 
  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值