springboot-分页功能

news2025/2/25 12:37:53

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());
    });
});

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/427459.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

redis设计与实现读书笔记

这里主要记录一下在阅读redis设计与实现中碰到的一些没有记录过的知识。 引用计数技术 Redis的对象系统实现了基于引用计数技术的内存回收机制&#xff0c;当程序不再使用某个对象的时候&#xff0c;这个对象所占用的内存就会被自动释放;另外&#xff0c;Redis还通过引用计数…

低调且强大--iVX低代码平台

iVX目录前言一、低代码那么多 为什么选择iVX&#xff1f;二、“拼”出来的低代码平台&#xff0c;真的好用吗&#xff1f;三、iVX与其他低代码有啥可比性&#xff1f;前言 首先我们应该明白自动编程突破可能是&#xff1a;领域内Mini LLM 现在的思路都是搞LLM&#xff0c;几乎像…

通俗举例讲解动态链接、静态链接

参考动态链接 - 知乎 加上我自己的理解&#xff0c;比较好懂&#xff0c;但可能在细节方面有偏差,但总体是一致的 静态链接的背景 静态链接使得不同的程序开发者和部门能够相对独立的开发和测试自己的程序模块&#xff0c;从某种意义上来讲大大促进了程序开发的效率&#xf…

NPC 也有了生命?当 ChatGPT 注入游戏你能想象吗

&#x1f34e;道阻且长&#xff0c;行则将至。&#x1f353; 目录引言&#xff1a;西部世界元宇宙&#xff0c;还记得吗ChatGPT 的世界&#xff1f;下图就是一个 ChatGPT 小镇&#xff1a; 引言&#xff1a;西部世界 《西部世界》以一个虚构的游戏般的“西部世界”为背景&am…

springboot验证码生成及验证功能

1.easy-captcha工具包 生成验证码的方式有许多种&#xff0c;这里选择的是easy-captcha工具包。 github开原地址为&#xff1a;easy-captcha工具包 其支持Java图形验证码&#xff0c;支持gif、中文、算术等类型&#xff0c;可用于Java Web、JavaSE等项目。 2添加依赖 首先需…

SQL Server的死锁说明

死锁指南一、了解死锁二、检测并结束死锁2.1、可能死锁的资源三、处理死锁四、最大限度地减少死锁4.1、以相同的顺序访问对象4.2、避免事务中的用户交互4.3、保持交易简短且在一个批次中4.4、使用较低的隔离级别4.5、使用基于行版本控制的隔离级别4.6、使用绑定连接4.7、停止事…

【云原生|Docker】04-docker的资源限制

目录 前言 容器的生命周期 1. 容器的启动过程 2. 容器的生命周期 ​编辑 内存限制 1. 内存限制的相关参数 2. 内存限制方式 2.1 设置-m,--memory&#xff0c;不设置--memory-swap 2.2 设置-m,--memorya&#xff0c;--memory-swapb&#xff0c;且b >a 2.…

本地从0搭建Stable Diffusion WebUI及错误记录

从0开始搭建本地Stable Diffusion WebUI环境 一.环境配置 1.使用的电脑配置 系统Windows10处理器英特尔 i7内存24GB显卡NVIDIA GTX 1060(6GB) 2.镜像源 阿里云 清华大学 中国科技大学 3.电脑环境变量配置 我的电脑–属性–高级系统设置–系统属性(高级)–环境变量 新建…

spring框架注解

3.Spring有哪些常用注解呢&#xff1f; Spring常用注解 Web: Controller&#xff1a;组合注解&#xff08;组合了Component注解&#xff09;&#xff0c;应用在MVC层&#xff08;控制层&#xff09;。 RestController&#xff1a;该注解为一个组合注解&#xff0c;相当于Con…

首个ChatGPT开发的应用上线;ChatMind思维导图工具;中文提示词大全;Copilot平替 | ShowMeAI日报

&#x1f440;日报&周刊合集 | &#x1f3a1;生产力工具与行业应用大全 | &#x1f9e1; 点赞关注评论拜托啦&#xff01; &#x1f916; 『一本与众不同的AI绘本』ChatGPT 编写故事 Midjourney 绘制插图 作者的女儿特别喜欢迪士尼动画《海洋奇缘》里的主人公莫阿娜&#…

Mybatis分解式查询

目录 一、Mybatis一对多分解式查询 1. 新增持久层接口方法 2. 新增映射文件对应的标签 3. 新增测试方法 4. 运行效果 二、Mybatis一对一分解式查询 1. 新增持久层接口方法 2. 新增映射文件对应的标签 3. 新增测试方法 4. 运行效果 三、Mybatis延迟加载 1. 开启延迟加…

超实用的十个超级实用事半功倍的Python自动化脚本

一淘模板 56admin.com在日常的工作学习当中&#xff0c;我们总会遇到各式各样的问题&#xff0c;其中不少的问题都是一遍又一遍简单重复的操作&#xff0c;不妨直接用Python脚本来自动化处理&#xff0c;今天小编就给大家分享十个Python高级脚本&#xff0c;帮助我们减少无谓的…

【数据结构与算法】栈的实现(附源码)

目录 一.栈的概念和结构 二.接口实现 A.初始化 Stackinit 销毁 Stackdestroy 1.Stackinit 2.Stackdestroy B.插入 Stackpush 删除 Stackpop 1.Stackpush 2.Stackpop C.出栈 Stacktop D. 栈的有效元素 Stacksize 判空 Stackempty 1.Stacksize 2.Stackempty …

Flink进阶篇-CDC 原理、实践和优化采集到Doris中

简介 基于doris官方用doris构建实时仓库的思路&#xff0c;从flinkcdc到doris实时数仓的实践。 原文 Apache Flink X Apache Doris 构建极速易用的实时数仓架构 (qq.com) 前提-Flink CDC 原理、实践和优化 CDC 是什么 CDC 是变更数据捕获&#xff08;Change Data Captur…

Spring《三》DI依赖注入

&#x1f34e;道阻且长&#xff0c;行则将至。&#x1f353; 上一篇&#xff1a;Spring《二》bean的实例化与生命周期 下一篇&#xff1a;敬请期待 目录一、setter注入&#x1f349;1.注入引用数据类型2.注入简单数据类型二、构造器注入&#x1f34a;1.注入引用数据类型2.简单数…

数据挖掘(2.3)--数据预处理

目录 三、数据集成和转换 1.数据集成 2.数据冗余性 2.1 皮尔森相关系数 2.2卡方检验 3.数据转换 四、数据的规约和变换 1.数据归约 2数据离散化 三、数据集成和转换 1.数据集成 数据集成是将不同来源的数据整合并一致地存储起来的过程。 不同来源的数据可能有不同…

Qt优秀开源项目之十七:QtPromise

QtPromise是Promises/A规范的Qt/C实现。该规范的译文见附录。 QtPromise基于Qt5.6及以上版本&#xff0c;当然也包括Qt6。 github地址&#xff1a;https://github.com/simonbrunel/qtpromise 新手导航&#xff1a;Getting Started | QtPromise API手册&#xff1a;API Referenc…

详解Spring、SpringBoot、SpringCloud三者的联系与区别

一、Spring二、Spring Boot三、Spring Cloud四、三者的关系一、Spring Spring 是一个轻量级的Java 开发框架&#xff0c;主要依存于SSM 框架&#xff0c;即Spring MVC Spring Mybatis&#xff0c;定位很明确&#xff0c;Spring MVC主要负责view 层的显示&#xff0c;Spring …

Scala 一文搞定

第一节&#xff1a;概述为什么学习Scala ?Apache Spark 是专为大规模数据快速实时处理的计算引擎/内存级大数据计算框架。Apache Spark 是由Scala 语言编写。Scala 与Java 关系总结三点:java 编译器与Scala 编译器可以相互使用。Java SDK 的类库可以被Scala使用&#xff0c;Sc…

理解什么是sql注入攻击 + xss攻击 + cors 攻击

SQL注入 SQL注入就是通过把SQL命令插入到Web表单提交或输入域名或页面请求的查询字符串&#xff0c;最终达到欺骗服务器执行恶意的SQL命令。 SQL注入攻击的总体思路: 寻找到SQL注入的位置判断服务器类型和后台数据库类型针对不同的服务器和数据库特点进行SQL注入攻击 SQL注入…