Web开发之分页功能

前言:

        💬本期文章所讲的功能是基于Web专栏中的文章代码基础进行补充:https://blog.csdn.net/yifei_345678/category_11705746.html?spm=1001.2014.3001.5482icon-default.png?t=M276https://blog.csdn.net/yifei_345678/category_11705746.html?spm=1001.2014.3001.5482

目录

分页功能:采用分页技术实现批量数据的页面显示 

1. 分页显示的好处

2.分页显示的实现步骤

3.案例:使用分页技术实现新闻展示页面的分页显示和查询 

数据库中的操作

Eclipse中的操作 


分页功能:采用分页技术实现批量数据的页面显示 

1. 分页显示的好处

  • 能显示多条信息
  • 不需要:像列表显示数据那样需要拖动页面

2.分页显示的实现步骤

  • 确定每页显示的数据数量
  • 计算显示的页数
  • 编写SQL语句 

3.案例:使用分页技术实现新闻展示页面的分页显示和查询 

数据库中的操作

先找到新闻表,并在表中插入多条数据,以便展示分页功能:

💬:在表上右键点击编辑数据就可以进行数据的插入操作了

数据行数与需要显示的页数之间的关系

int page=1 --当前的页数
int rows=2 --每页显示的行数

page:1 【1(begin开始位置),5(end结束位置)】
page:2 【5,10】
page:3 【10,15】
//找规律:
begin 开始行数: (page-1)*rows+1
end 结束行数: page*rows

编写分页功能的SQL语句 

错误示例:

如上图所示,如果使用新闻的id来进行分页查询展示,那么,当其中一条数据被删除后,新闻id也会被删除,不利于分页查询与展示,所以,这里推荐使用伪列(rownum)来进行SQL语句编写:

推荐使用rownum,是因为rownum不会因为数据的删除而被删除,一直会从1向后排序,相当于行数据的编号:

但是要注意,rownum不能使用大于1来作为查询条件,如果要使用大于1来作为查询条件,要将伪列转变成实列:

select * from (
	select a.*,rownum row1 from t2_news a where news_title like ?
)b where row1 between ? and ?;

Eclipse中的操作 

需要编写代码的界面

 index.jsp界面代码:

<%@page import="web_06.com.pojo.News"%>
<%@page import="web_06.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界面代码:

package web_06.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
	}
	
}

效果展示:

index。jsp界面:

点击链接2后:

点击下一页(上一页同理):查询后:


感 谢 阅 读 ^_^

  • 15
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 9
    评论
教学-传智播客-项目视频经典之作巴巴运动网106集-27实现Web层的分页功能源代码 所需要的jar文件: (一)、Hibernate: 位于 "\hibernate-distribution-3.3.2.GA" 目录下的jar文件: hibernate3.jar 位于 "\hibernate-distribution-3.3.2.GA\lib\required" 目录下的jar文件: (共7个) antlr-2.7.6.jar commons-collections-3.1.jar dom4j-1.6.1.jar javassist-3.9.0.GA.jar jta-1.1.jar slf4j-api-1.5.8.jar slf4j-nop-1.5.2.jar (二)、JPA: 位于 "\Hibernate\hibernate-entitymanager3.4.0.GA" 目录下的jar文件: hibernate-entitymanager.jar ejb3-persistence.jar hibernate-annotations.jar hibernate-commons-annotations.jar (三)、Spring: 位于 "\spring-framework-2.5.5\dist" 目录下的jar文件: spring.jar 位于 "\spring-framework-2.5.5\lib\aspectj" 目录下的jar文件: (共3个) aspectjrt.jar aspectjweaver.jar 位于 "\spring-framework-2.5.5\lib\cglib" 目录下的jar文件: (共1个) cglib-nodep-2.1_3.jar 位于 "\spring-framework-2.5.5\lib\j2ee\" 目录下的jar文件: common-annotations.jar 位于 "\spring-framework-2.5.5\lib\jakarta-commons" 目录下的jar文件: commons-dbcp.jar commons-pool.jar commons-logging.jar (四)、Struts: 位于 "\Struts\struts-1.3.10\struts-1.3.10-all\struts-1.3.10\lib" 目录下的jar文件: (共20个) antlr-2.7.2.jar(与Hibernate所含antlr-2.7.6.jar文件重复,删除) bsf-2.3.0.jar commons-beanutils-1.8.0.jar commons-chain-1.2.jar commons-digester-1.8.jar commons-fileupload-1.1.1.jar commons-io-1.1.jar commons-logging-1.0.4.jar commons-validator-1.3.1.jar jstl-1.0.2.jar(改为:\spring-framework-2.5.5\lib\j2ee\jstl.jar) oro-2.0.8.jar standard-1.0.6.jar(改为:\spring-framework-2.5.5\lib\jakarta-taglibs\standard.jar) struts-core-1.3.10.jar struts-el-1.3.10.jar struts-extras-1.3.10.jar struts-faces-1.3.10.jar struts-mailreader-dao-1.3.10.jar struts-scripting-1.3.10.jar struts-taglib-1.3.10.jar struts-tiles-1.3.10.jar (五)、Spring+Struts: \spring-framework-2.5.5\dist\modules\spring-webmvc-struts.jar MySQL: mysql-connector-java-5.1.16-bin.jar 运行: http://localhost:8090/control/center/main.do

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值