springboot-分页功能

2023-10-27

1.分页功能的作用

分页功能作为各类网站和系统不可或缺的部分(例如百度搜索结果的分页等)
,当一个页面数据量大的时候分页作用就体现出来的,其作用有以下5个。
(1)减少系统资源的消耗
(2)提高数据库的查询性能
(3)提升页面的访问速度
(4)符合用户的浏览习惯
(5)适配页面的排版

2.建立测试数据库

由于需要实现分页功能,所需的数据较多

DROP TABLE IF EXISTS tb_user;

CREATE TABLE tb_user (
    id int(11) NOT NULL AUTO_INCREMENT COMMENT '主键id',
    name varchar(100) NOT NULL DEFAULT '' COMMENT '登录名',
    password varchar(100) NOT NULL DEFAULT '' COMMENT '密码',
    PRIMARY KEY (id) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8;

insert into tb_user (id,name,password)
value (1,'C','123456'),
(2,'C++','123456'),
(3,'Java','123456'),
(4,'Python','123456'),
(5,'R','123456'),
(6,'C#','123456');

insert into tb_user (id,name,password) value (7,'test1','123456');
insert into tb_user (id,name,password) value (8,'test2','123456');
insert into tb_user (id,name,password) value (9,'test3','123456');
insert into tb_user (id,name,password) value (10,'test4','123456');
insert into tb_user (id,name,password) value (11,'test5','123456');
insert into tb_user (id,name,password) value (12,'test6','123456');
insert into tb_user (id,name,password) value (13,'test7','123456');
insert into tb_user (id,name,password) value (14,'test8','123456');
insert into tb_user (id,name,password) value (15,'test9','123456');
insert into tb_user (id,name,password) value (16,'test10','123456');
insert into tb_user (id,name,password) value (17,'test11','123456');
insert into tb_user (id,name,password) value (18,'test12','123456');
insert into tb_user (id,name,password) value (19,'test13','123456');
insert into tb_user (id,name,password) value (20,'test14','123456');
insert into tb_user (id,name,password) value (21,'test15','123456');
insert into tb_user (id,name,password) value (22,'test16','123456');
insert into tb_user (id,name,password) value (23,'test17','123456');
insert into tb_user (id,name,password) value (24,'test18','123456');
insert into tb_user (id,name,password) value (25,'test19','123456');
insert into tb_user (id,name,password) value (26,'test20','123456');
insert into tb_user (id,name,password) value (27,'test21','123456');
insert into tb_user (id,name,password) value (28,'test22','123456');
insert into tb_user (id,name,password) value (29,'test23','123456');
insert into tb_user (id,name,password) value (30,'test24','123456');
insert into tb_user (id,name,password) value (31,'test25','123456');
insert into tb_user (id,name,password) value (32,'test26','123456');
insert into tb_user (id,name,password) value (33,'test27','123456');
insert into tb_user (id,name,password) value (34,'test28','123456');
insert into tb_user (id,name,password) value (35,'test29','123456');
insert into tb_user (id,name,password) value (36,'test30','123456');
insert into tb_user (id,name,password) value (37,'test31','123456');
insert into tb_user (id,name,password) value (38,'test32','123456');
insert into tb_user (id,name,password) value (39,'test33','123456');
insert into tb_user (id,name,password) value (40,'test34','123456');
insert into tb_user (id,name,password) value (41,'test35','123456');
insert into tb_user (id,name,password) value (42,'test36','123456');
insert into tb_user (id,name,password) value (43,'test37','123456');
insert into tb_user (id,name,password) value (44,'test38','123456');
insert into tb_user (id,name,password) value (45,'test39','123456');
insert into tb_user (id,name,password) value (46,'test40','123456');
insert into tb_user (id,name,password) value (47,'test41','123456');
insert into tb_user (id,name,password) value (48,'test42','123456');
insert into tb_user (id,name,password) value (49,'test43','123456');
insert into tb_user (id,name,password) value (50,'test44','123456');
insert into tb_user (id,name,password) value (51,'test45','123456');

3.分页功能返回的结果封装

新建一个util包并在包中新建Result通用结果类,代码如下:

package ltd.newbee.mall.entity;

public class User {
    private Integer id;
    private String name;
    private String password;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

后端接口返回的数据会根据以上格式进行数据封装,包括业务码、返回信息、实际的数据结果。这个格式是开发人员自行设置的,如果有其他更好的方案也可以进行适当的调整。

在util包中新建PageResult通用结果类,代码如下:

package ltd.newbee.mall.util;

import java.util.List;

/**
 * 分页工具类
 */
public class PageResult {
    //总记录数
    private int totalCount;
    //每页记录数
    private int pageSize;
    //总页数
    private int totalPage;
    //当前页数
    private int currPage;
    //列表数据
    private List<?> list;

    /**
     *
     * @param totalCount 总记录数
     * @param pageSize 每页记录数
     * @param currPage 当前页数
     * @param list 列表数据
     */
    public PageResult(int totalCount, int pageSize, int currPage, List<?> list) {
        this.totalCount = totalCount;
        this.pageSize = pageSize;
        this.currPage = currPage;
        this.list = list;
        this.totalPage = (int) Math.ceil((double) totalCount / pageSize);
    }

    public int getTotalCount() {
        return totalCount;
    }

    public void setTotalCount(int totalCount) {
        this.totalCount = totalCount;
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    public int getTotalPage() {
        return totalPage;
    }

    public void setTotalPage(int totalPage) {
        this.totalPage = totalPage;
    }

    public int getCurrPage() {
        return currPage;
    }

    public void setCurrPage(int currPage) {
        this.currPage = currPage;
    }

    public List<?> getList() {
        return list;
    }

    public void setList(List<?> list) {
        this.list = list;
    }
}

4.分页功能代码具体实现

4.1数据层

在UserDao接口中新增两个方法findUsers()和getTotalUser(),代码如下所示:

/**
     * 返回分页数据列表
     * 
     * @param pageUtil
     * @return
     */
    List<User> findUsers(PageQueryUtil pageUtil);

    /**
     * 返回数据总数
     * 
     * @param pageUtil
     * @return
     */
    int getTotalUser(PageQueryUtil pageUtil);

在UserMapper.xml文件中新增这两个方法的映射语句,代码如下所示:

<!--分页-->
    <!--查询用户列表-->
    <select id="findUsers" parameterType="Map" resultMap="UserResult">
        select id,name,password from tb_user
        order by id desc
        <if test="start!=null and limit!=null">
            limit #{start}.#{limit}
        </if>
    </select>
    <!--查询用户总数-->
    <select id="getTotalUser" parameterType="Map" resultType="int">
        select count(*) from tb_user
    </select>

4.2业务层

新建service包,并新增业务类UserService,代码如下所示:

import ltd.newbee.mall.dao.UserDao;
import ltd.newbee.mall.entity.User;
import ltd.newbee.mall.util.PageResult;
import ltd.newbee.mall.util.PageQueryUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService {

    @Autowired
    private UserDao userDao;

    public PageResult getUserPage(PageQueryUtil pageUtil){
        //当前页面中的数据列表
        List<User> users = userDao.findUsers(pageUtil);
        //数据总条数,用于计算分页数据
        int total = userDao.getTotalUser(pageUtil);
        //分页信息封装
        PageResult pageResult = new PageResult(users,total,pageUtil.getLimit(),pageUtil.getPage());
        return pageResult;
    }
}

首先根据当前页面和每页条数查询当前页的数据集合,然后调用select count(*)语句查询数据的总条数用于计算分页数据,最后将获取的数据封装到PageResult对象中并返回给控制层。

4.3控制层

在controller包中新建PageTestController类,用于实现分页请求的处理并返回查询结果,代码如下所示:

@RestController
@RequestMapping("users")
public class PageTestController {

    @Autowired
    private UserService userService;

    //分页功能测试
    @RequestMapping(value = "/list",method = RequestMethod.GET)
    public Result list(@RequestParam Map<String,Object> params){
        Result result = new Result();
        if (StringUtils.isEmpty(params.get("page"))||StringUtils.isEmpty(params.get("limit"))){
            //返回错误码
            result.setResultCode(500);
            //错误信息
            result.setMessage("参数异常!");
            return result;
        }
        //封装查询参数
        PageQueryUtil queryParamList = new PageQueryUtil(params);
        //查询并封装分页结果集
        PageResult userPage = userService.getUserPage(queryParamList);
        //返回成功码
        result.setResultCode(200);
        result.setMessage("查询成功");
        //返回分页数据
        result.setData(userPage);
        return result;
    }
}

分页功能的交互流程:前端将所需页码和条数参数传输给后端,后端在接收分页请求后对分页参数进行计算,并利用MySQL的limit关键字查询对应的记录,在查询结果被封装后返回给前端。在TestUserControler类上使用的是@RestController注解,该注解相当于@ResponseBody+@Controller的组合注解。

5.jqGrid分页插件

jqGrid是一个用来显示网格数据的jQuery插件。开发人员通过使用jqGrid可以轻松实现前端页面与后台数据的Ajax异步通信并实现分页功能。同时,jqGrid是一款代码开源的分页插件,源码也一直处于迭代更新的状态中。
下载地址:jqGrid
下载jqGrid后解压文件,将解压的文件直接拖进项目的static目录下
在这里插入图片描述
以下是jqGrid实现分页的步骤:
首先,在前端页面代码中引入jqGrid分页插件所需的源文件,代码如下所示:

<link href="plugins/jqgrid-5.8.2/ui.jqgrid-bootstrap4.css" rel="stylesheet"/>
<!--jqGrid依赖jQuery,因此需要先引入jquery.min.js文件,下方地址为字节跳动提供的cdn地址-->
<script src="http://s3.pstatp.com/cdn/expire-1-M/jquery/3.3.1/jquery.min.js"></script>
<!--grid.locale-cn.js为国际化所需的文件,-cn表示中文-->
<script src="plugins/jqgrid-5.8.2/grid.locale-cn.js"></script>
<script src="plugins/jqgrid-5.8.2/jquery.jqGrid.min.js"></script>

其次,在页面中需要展示分页数据的区域添加用于jqGrid初始化的代码:

<!--jqGrid必要DOM,用于创建表格展示列表数据-->
<table id="jqGrid" class="table table-bordered"></table>

<!--jqGrid必要DOM,分页信息区域-->
<div id="jqGridPager"></div>

最后,调用jqGrid分页插件的jqGrid()方法渲染分页展示区域,代码如下所示:
请添加图片描述

请添加图片描述

jqGrid()方法中的参数及含义如图所示。
请添加图片描述
jqGrid前端页面测试:
在resources/static目中新建jqgrid-page-test.html文件,代码如下所示:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>jqGrid分页测试</title>
    <!--引入bootstrap样式文件-->
    <link rel="stylesheet" href="/static/bootstrap-5.3.0-alpha3-dist/css/bootstrap.css"/>
    <link href="jqGrid-5.8.2/css/ui.jqgrid-bootstrap4.css" rel="stylesheet"/>
</head>
<body>
<div style="margin: 24px;">
    <!--数据展示列表,id为jqGrid-->
    <table id="jqGrid" class="table table-bordered"></table>
    <!--分页按钮展示区-->
    <div id="jqGridPager"></div>
</div>
</body>
<!--jqGrid依赖jQuery,因此需要先引入jquery.min.js文件,下方地址为字节跳动提供的cdn地址-->
<script src="http://s3.pstatp.com/cdn/expire-1-M/jquery/3.3.1/jquery.min.js"></script>
<!--grid.locale-cn.js为国际化所需的文件,-cn表示中文-->
<script src="plugins/jqgrid-5.8.2/grid.locale-cn.js"></script>
<script src="plugins/jqgrid-5.8.2/jquery.jqGrid.min.js"></script>
<script src="jqgrid-page-test.js"></script>
</html>

jqGrid初始化
在resources/static目录下新建jqgrid-page-test.js文件,代码如下所示:

$(function () {
    $("#jqGrid").jqGrid({
        url: 'users/list',
        datatype: "json",
        colModel: [
            {label: 'id',name: 'id', index: 'id', width: 50, hidden: true,key:true},
            {label: '登录名',name: 'name',index: 'name', sortable: false, width: 80},
            {label: '密码字段',name: 'password',index: 'password', sortable: false, width: 80}
        ],
        height: 485,
        rowNum: 10,
        rowList: [10,30,50],
        styleUI: 'Bootstrap',
        loadtext: '信息读取中...',
        rownumbers: true,
        rownumWidth: 35,
        autowidth: true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader:{
            root: "data.list",
            page: "data.currPage",
            total: "data.totalCount"
        },
        prmNames:{
            page: "page",
            rows: "limit",
            order: "order"
        },
        gridComplete: function () {
            //隐藏grid底部滚动条
            $("#jqGrid").closest(".ui-jqgrid-bdiv").css({"overflow-x": "hidden"});
        }
    });
    $(window).resize(function () {
        $("jqGrid").setGridWidth($(".card-body").width());
    });
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

springboot-分页功能 的相关文章

随机推荐

  • BUG -- 背景图片 background-postion 值为 百分比 时无效

    最近再写公司官网 要求响应式 为了图方便用百分比遇到一个bug 经过多方测试 此时遇到的问题是 当background size的值与容器的width height值相同时 同为px或者 background postion属性值设置为百分
  • 毕业设计-基于人工智能的脱机手写数字识别系统

    目录 前言 课题背景和意义 实现技术思路 一 相关背景知识介绍 二 基于智能优化算法的SVM在手写数字中的应用 三 基于智能优化算法的KELM在手写数字中的应用 实现效果图样例 最后 前言 大四是整个大学期间最忙碌的时光 一边要忙着备考或实
  • js爬虫反扒

    3 js动态网页抓取方式 重点 许多时候爬虫取到的页面仅仅是一个静态的页面 即网页的源代码 就像在浏览器上的 查看网页源代码 一样 一些动态的东西如javascript脚本执行后所产生的信息是抓取不到的 下面两种方案 可用来python爬取
  • MyBatis—利用MyBatis查询(查询所有,查询一行,条件查询)

    文章目录 1 查询所有 2 查询详情 通过特定属性查询 3 多条件查询 1 接口参数列表三种表达方式 2 多条件查询 3 动态Sql 4 多条件动态查询 5 单条件动态查询 1 查询所有 基本步骤 1 定义mapper接口 编写接口方法 2
  • 常用算法之分治算法(如何解决汉诺塔问题)

    1 什么是分治算法 分治 从字面上解释就是 分而治之 将一个复杂的问题分解成为两个或者更多的相同或者相似的子问题 再把子问题分成更小的子问题 直到最后的子问题简单到可以直接求解 原问题的解就是子问题解的合并 复杂问题 gt 子问题 gt 更
  • 目标检测框架在目标跟踪中的应用

    目标检测框架在目标跟踪中的应用 从SiamRPN将跟踪问题定义为one shot detection任务之后 出现了大量将检测组件由于跟踪的研究 不过Siamese系列一个很大的问题在于其本质仍然是一个模板匹配问题 网络关注的是寻找与tar
  • 100天精通Python(基础篇)——第15天:布尔类型和比较运算符

    文章目录 布尔类型 比较运算符 示例代码 布尔类型 True 表示真 False 表示假 比较运算符 示例代码 bool 1 True bool 2 False print f bool 1 bool 1 类型 type bool 1 pr
  • [转载] 机器学习数据集统计系列(二)

    金融 美国劳工部统计局官方发布数据 房地产公司 Zillow 公开美国房地产历史数据 沪深股票除权除息 配股增发全量数据 截止 2016 12 31 上证主板日线数据 截止 2017 05 05 原始价 前复权价 后复权价 1260支股票
  • 很抱歉,EXCEL遇到错误,使其无法正常工作,因此需要关闭EXCEL。是否希望我们立即修复?...

    出现以上情况解决方式 按Windows R 输入 regedit 打开注册表 找到以下键值 HKEY CURRENT USER SOFTWARE Microsoft Office 16 0 Excel Options 在右侧新建DWORD值
  • 收藏:程序员必选其一的好用的15种文本编辑器

    很多时候比如编程查看代码或者打开各种文档下我们都会用到文本编辑器 Windows自带的记事本功能很简陋并且打开大文件很慢 因此很多童鞋都会有自己喜欢的一款文本编辑器 在这里 西西挑选前15个最佳的文本编辑器 这些编辑器实际上主要适合程序员
  • Java之命令提示符

    启动控制台 Window R 输入cmd回车即可打开 文件夹操作 盘之间的切换 gt 盘名称 PS 盘名大小写不做要求 在一个盘中进入文件夹 gt cd 空格 文件夹名字 返回上一级 gt cd 空格 or cd 直接回到根路径 PS 空格
  • 性能测试基础

    性能测试 一 性能测试的目的 二 五大性能指标 1 响应时间 2 并发用户数 3 吞吐量 4 思考时间 5 资源指标 三 测试方法 负载测试 找到最优负载量 压力测试 找到极限负载量 稳定性测试 关注长时间运行稳定性 并发测试 大量用户同一
  • windows系统下利用脚本批量修改文件夹下的文件属性

    步骤 1 在文件夹中新建一个文本文档 2 在文本文档中写入 ren 后缀 后缀 加号表示空格 如修改txt到csv则输入ren txt csv 3 保存文本文档 并修改后缀为bat格式 4 双击运行即可
  • mybatis批量更新 一条成功,多条失败

  • 上班族做什么副业赚钱?全面解析副业赚钱模式!

    每个人做事都需要输出精力 你的精力放在哪 时间就在哪 产生的结果也在哪 最近可能是大家对副业赚钱呼声最高的时候 怎么找到副业 如何做副业 是现阶段更多人在思考的问题 网上流行十多年的网赚事业 可能是想找副业的人首先想到的领域 我为什么把精力
  • window.history.go(-1)

    window history go 1 返回上一页
  • 鸿蒙设备开发实战8

    第7章 设备联网上云 7 1 对接华为云iot平台 华为云iot平台介绍 华为云物联网平台即华为设备接入服务 loT Device Access 提供海量设备连接上云 设备和云端 双向消息通信 批量设备管理 远程控制和监控 OTA升级 设备
  • 手撸代码-括号序列

    思路 1 利用栈的后进先出的特点 遇到左括号入栈 遇到右括号则将栈顶元素与右括号判断是否相等 不相等则不是合法的括号序列 2 循环结束后 栈为空 说明不是合法的括号序列 public boolean isValid String s Vec
  • 常见算法笔试或面试题

    Problem 1 Is it a loop 判断链表是否有环 Assume that wehave a head pointer to a link list Also assumethat we know the list is sin
  • springboot-分页功能

    1 分页功能的作用 分页功能作为各类网站和系统不可或缺的部分 例如百度搜索结果的分页等 当一个页面数据量大的时候分页作用就体现出来的 其作用有以下5个 1 减少系统资源的消耗 2 提高数据库的查询性能 3 提升页面的访问速度 4 符合用户的