Web的分页功能

新闻数据分页


此功能为 新闻项目的补充。

分页功能最难实现的就是SQL语句的编写

我们先找出数据行数与需要显示的页数之间的关系

int page=1 //当前的页数
int rows=5 //每页显示的行数
 
page:1 [1(begin开始位置)5(end结束位置)]
page:2 [610]
page:3 [1115]
//找规律:
begin 开始行数: (page-1)*rows+1
end 结束行数: page*rows

然后让我们来编写SQL语句(如果想要让数据按ID排序的话就还要在插入伪列之前进行子查询排序)

SELECT * FROM (
	SELECT A.*,ROWNUM ROW1 FROM T_NEWS A WHERE NEWS_TITLE LIKE ?
)B WHERE ROW1 BETWEEN ? AND ?;

index.jsp:管理员主页

<%@page import="News_Project.com.pojo.News"%>
<%@page import="News_Project.com.dao.NewsDao"%>
<%@page import="java.nio.charset.StandardCharsets"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="java.sql.DriverManager" %>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.PreparedStatement" %>
<%@ page import="java.sql.ResultSet" %>
<!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="${pageContext.request.contextPath}/bootstrap-3.3.7-dist/css/bootstrap.css" rel="stylesheet">
    <script src="${pageContext.request.contextPath}/bootstrap-3.3.7-dist/js/jquery-3.5.1.js"></script>
    <script src="${pageContext.request.contextPath}/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>
 
<!-- include包含,可以用它导入别的页面 -->
<!-- 这样就算在路径上输入除了登录注册之外的界面路径也会调到登录界面除非登录成功 -->
<%@include file="top.jsp"%>
 
<ol class="breadcrumb">
    <li>您当前的位置是</li>
    <li>新闻发布系统</li>
    <li class="active">首页</li>
</ol>
<!--主界面的表单要设置action,每个表单最好都设置,post可以让id不显示在路径上-->
<form action="${pageContext.request.contextPath}/index.jsp" method="post" class="form-inline" style="margin: 0 auto 20px;">
    <div class="form-group" style="display: block;text-align: center;">
        <div class="input-group">
            <div class="input-group-addon">新闻标题</div>
            <!--表单提交的时候会将name属性的值带到路径上-->
            <input name="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">
        <%
       //拿到当前用户进行分页的名字叫page1
       String page1=request.getParameter("page");
        request.setCharacterEncoding("UTF-8");
        //用户第一次进入主界面时没在路径上带上page=null,则默认为第一页:
        int n=1;//n:页面数
        if(page1!=null){
        	n=Integer.parseInt(page1);//不为null时设置为你携带的页面数
        }        
        //如何取到路径上的表单查询框值newName:
        String newName=request.getParameter("newName");       
        //查询当前数据对应的最大页数
        int maxPage=new NewsDao().queryPageCount(newName);      
        //根据页数查询数据
        //当从登陆界面进入主界面时,newName=null,所以要在主界面用""做模糊查询显示所有已发布新闻
        if(newName==null){
        	newName="";//查询所有数据
        }  
        //破碎重组:防止newName乱码,字符.getBytes拿到字节,并转成中文
       newName=new String(newName.getBytes(StandardCharsets.ISO_8859_1),StandardCharsets.UTF_8);
            //结果集中有很多数据
            for(News news : new NewsDao().queryByName(newName,n)){
        %>
        <!--两个《%%》里面的内容会跟随迭代器一起迭代-->
        <li class="list-group-item">
            <h4 class="list-group-item-heading">
            	<!-- ?newId= 取到get路径上的值,将数据库中的id传给read界面 -->
                <a href=" ${pageContext.request.contextPath}/read.jsp?newId=<%=news.getNews_Id()%>"  data-placement="bottom" data-toggle="tooltip"  title="国家卫健委:昨日新增确诊病例29例,其中本土病例2例">
                    <%=news.getNews_titile()%>
                </a>
            </h4>
            <p class="list-group-item-text text-right">
            <!-- rs.getString(4)拿到数据库数据,=在网页打印 -->
                <span class="glyphicon glyphicon-user"><code><%=news.getNews_author() %></code></span>               
               <!-- 点击量 -->
                <span class="glyphicon glyphicon-time"><code><%=news.getNews_click()%></code></span>
            	<!-- 收藏量 -->
            	<span class="glyphicon glyphicon-time"><code><%=news.getNews_maker()%></code></span>
            	<span class="glyphicon glyphicon-time"><code><%=news.getNews_publisher()%></code></span>
            </p>
        </li>
        <%
            }
        %>
    </ul>
</div>
<div class="container text-center">
    <ul class="pagination" style="margin: 20px auto;">
        <li>
        <!-- 向前走一页n-->
        <!-- 当页数为1时就不-1了,也可以:n-1<1?1:n-1 -->
            <a href="index.jsp?page=<%=Math.max(n-1,1)%>&newName=<%=newName%>"><span>&laquo;</span></a>
        </li>
		<%
			//有几页就有几个链接:根据最大页数来动态生成链接
			for(int i=1;i<maxPage;i++){
		%>
		<!--如果遍历页数i==当前页数n,就激活-->
			 <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>

NewsDao.java:封装的java代码

package News_Project.com.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import web_06.com.pojo.News;
import web_06.com.util.DBHelper;
public class NewsDao {
	private Connection con;
	private PreparedStatement ps;
	private ResultSet rs;
	/**
	 * 模糊查询的方法
	 * @param newName
	 * @param page
	 * @return
	 */
	public List<News> queryByName(String newName,int page/*让别人传入页面数*/) {
		//int page=1;//页面数:要放到跳转网页链接的跳转路径中取
		int rows=5;//数据条数
		int begin=1+((page-1)*rows);//开始位置,between ? 
	    int end=page*rows;//结束位置 and ?
		List<News> list=new ArrayList<News>();
		try {
			con=DBHelper.getCon();
			ps=con.prepareStatement("select * from ("
					+ " select a.*,rownum row1 from t2_news a where news_title like ?"
					+ ")b where row1 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.setNews_Id(rs.getInt(1));
				news.setNews_titile(rs.getString(2));
				news.setNews_topic(rs.getInt(3));
				news.setNews_author(rs.getString(4));
				news.setNews_publisher(rs.getString(5));
				news.setNews_click(rs.getInt(6));
				news.setNews_maker(rs.getInt(7));
				news.setNews_content(rs.getString(8));
				news.setNews_cover(rs.getString(9));
				//将新闻对象添加到集合中
				list.add(news);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			DBHelper.close(con, ps, rs);
		}
		return list;
	}
	/**
	 * 查询最大显示页面数的方法
	 * @param newName
	 * @return
	 */
	//页数应该是根据当前有的页数来前进或后退
	//当前有的页数=数据库的数据条数 /除 每页条数
	//当前有的页数  返回int
	public int queryPageCount(String newName) {
		//int page=1;//页面数:要放到跳转网页链接的跳转路径中取
		int rows=5;//数据条数
		int count=0;//数据库中数据的条数
		try {
			con=DBHelper.getCon();
			//根据模糊查询的新闻名字显示新闻条数
			ps=con.prepareStatement("select count(1) from t2_news where news_title like ?");
			//占位符赋值
            ps.setString(1,"%"+newName+"%");
            //得到结果集
			rs=ps.executeQuery();
			if(rs.next()) {
				count=rs.getInt(1);//拿到数据库的条数
			}
			//System.out.println(count+"-------");
			//返回页面数:/是求整不是除,count*1.0变成小数,除后结果也为小数
			return new Double(Math.ceil(count*1.0/rows)).intValue();
			//return Integer.parseInt(Math.ceil(count*1.0/rows)+"");这个不行!
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			DBHelper.close(con, ps, rs);
		}
		return 0;//数据库数据条数为0
	}
	
}
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

绥彼岸

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值