springboot-分页功能

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.mfbz.cn/a/13720.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

Vue 3组件传值 、组件通信

本文采用<script setup />的写法&#xff0c;比options API更自由。那么我们就来说说以下七种组件通信方式&#xff1a; props emit v-model refs provide/inject eventBus vuex/pinia 举个例子 本文将使用下面的演示&#xff0c;如下图所示&#xff1a; 上图中…

mybatis粗心使用导致内存溢出

现象 服务响应变慢&#xff0c;线程日志也出现Java heap space内存溢出的错误&#xff0c;这个服务属于基础业务服务&#xff0c;出现问题要尽快的排查 分析 因为设置了gc日志和jmap启动相关参数 所以我们进行分析&#xff0c;这里模拟线上环境将堆大小参数调整到了128m&am…

【Linux】权限管理

文章目录 &#x1f4d6; 前言1. 什么是权限2. 权限管理2.1 Linux的用户分类&#xff1a;2.2 Liunx文件的分类&#xff1a;2.3 文件的访问权限2.4 文件访问权限的相关设置方法&#xff1a;chmod对文件权限的修改chown / chgrp 2.5 以八进制修改文件权限&#xff1a;2.6 默认权限…

Springsecurity课程笔记06-13章基于数据库的方法授权

动力节点Springsecurity视频课程 6 密码处理 6.1 为什么要加密&#xff1f; csdn 密码泄露事件 泄露事件经过&#xff1a;https://www.williamlong.info/archives/2933.html 泄露数据分析&#xff1a;https://blog.csdn.net/crazyhacking/article/details/10443849 6.2加密…

IJKPLAYER源码分析-常用API

前言 本文简要介绍IJKPLAYER的几个常用API&#xff0c;以API使用的角度&#xff0c;来审视其内部运作原理。这里以iOS端直播API调用切入。 调用流程 init 创建播放器实例后&#xff0c;会先调用init方法进行初始化&#xff1a; - (IJKFFMediaPlayer *)init {self [super ini…

计算机网络复习题+答案

文章目录 导文题目一、单项选择题二、填空题三、判断改错题,判断下列命题正误,正确的在其题干后的括号内打“√”,错误的打“”,并改正。四、名词解释五、简答题六、应用题导文 计算机网络复习题 题目 一、单项选择题 在应用层协议中,主要用于IP地址自动配置的协议是: (…

文案自动修改软件-文案自动改写的免费软件下载

文章生成器ai写作机器人 随着人工智能技术的飞速发展&#xff0c;越来越多的新型产品被推向市场。其中&#xff0c;文章生成器AI写作机器人是一个备受关注的新兴行业。它使用机器学习和自然语言处理等技术&#xff0c;为用户自动生成高质量的文章和内容&#xff0c;帮助用户在…

Python——第2章 数据类型、运算符与内置函数

目录 1 赋值语句 2 数据类型 2.1 常用内置数据类型 2.1.1 整数、实数、复数 2.1.2 列表、元组、字典、集合 2.1.3 字符串 2.2 运算符与表达式 2.2.1 算术运算符 2.2.2 关系运算符 2.2.3 成员测试运算符 2.2.4 集合运算符 2.2.5 逻辑运算符 2.3 常用内置…

本地搭建属于自己的ChatGPT:基于PyTorch+ChatGLM-6b+Streamlit+QDrant+DuckDuckGo

本地部署chatglm及缓解时效性问题的思路&#xff1a; 模型使用chatglm-6b 4bit&#xff0c;推理使用hugging face&#xff0c;前端应用使用streamlit或者gradio。 微调对显存要求较高&#xff0c;还没试验。可以结合LoRA进行微调。 缓解时效性问题&#xff1a;通过本地数据库…

Mybatis高级映射及延迟加载

准备数据库表&#xff1a;一个班级对应多个学生。班级表&#xff1a;t_clazz&#xff1b;学生表&#xff1a;t_student 创建pojo&#xff1a;Student、Clazz // Student public class Student {private Integer sid;private String sname;//...... }// Clazz public class Cla…

Flutter PC桌面端 控制应用尺寸是否允许放大缩小

一、需求 桌面端中&#xff0c;登录、注册、找回密码页面不允许用户手动放大缩小&#xff0c;主页面允许 二、插件 window_manager 使用教程请参照这篇博客&#xff1a;Flutter桌面端开发——window_manager插件的使用 题外话&#xff1a; 之前使用的是bitsdojo_window插件…

[golang gin框架] 25.Gin 商城项目-配置清除缓存以及前台列表页面数据渲染公共数据

配置清除缓存 当进入前台首页时,会缓存对应的商品相关数据,这时,如果后台修改了商品的相关数据,缓存中的对应数据并没有随之发生改变,这时就需要需改对应的缓存数据,这里有两种方法: 方法一 在管理后台操作直接清除缓存中的所有数据,当再次访问前台首页时,就会先从数据库中获取…

记frp内网穿透配置

这两天由于想给客户看一下我们的系统&#xff0c;于是想到用内网穿透&#xff0c;但是怎么办呢&#xff0c;没有用过呀&#xff0c;于是各处找资料&#xff0c;但是搞完以后已经不记得参考了那些文档了&#xff0c;对不起各位大神&#xff0c;就只能写出过程和要被自己蠢死的错…

初识C++(二)

在初识c&#xff08;一&#xff09;当中我们已经向大家介绍了四个c和C语言不同的使用方法。接下来我们再来向大家介绍另外的一些新的c语言的使用方法。 &#x1f335;引用 简单一点来说引用就是给已存在的变量起一个别名。这个别名通常的作用和C语言当中的指针类似。我们可以通…

牛客网刷题总结

1.利用%符号获取特定位数的数字。 2.强制类型转换 &#xff08;将float转换为int &#xff09; 3.计算有关浮点型数据时&#xff0c;要注意你计算过程中所有的数据都是浮点型 4.0/3.0 ! 4/3 4.通过位操作符实现输出2的倍数&#xff08;对于位操作符不熟悉的小伙伴可以看看我…

基于Java+SpringBoot+vue实现图书借阅和销售商城一体化系统

基于JavaSpringBootvue实现图书借阅和销售商城一体化系统 博主介绍&#xff1a;5年java开发经验&#xff0c;专注Java开发、定制、远程、指导等,csdn特邀作者、专注于Java技术领域 作者主页 超级帅帅吴 Java项目精品实战案例《500套》 欢迎点赞 收藏 ⭐留言 文末获取源码联系方…

电脑系统错误怎么办?您可以看看这5个方法!

案例&#xff1a;电脑出现系统错误该如何解决&#xff1f; 【这几天长时间使用我的电脑&#xff0c;导致它的系统出现了错误。有没有小伙伴知道如何解决电脑系统出错的问题&#xff1f;求一个能快速解决的方法。】 电脑系统出现错误是使用电脑时难免会遇到的问题之一&#xf…

【C++初阶】C++入门(二):引用内联函数auto关键字范围for循环(C++11)指针空值nullptr

​ ​&#x1f4dd;个人主页&#xff1a;Sherry的成长之路 &#x1f3e0;学习社区&#xff1a;Sherry的成长之路&#xff08;个人社区&#xff09; &#x1f4d6;专栏链接&#xff1a;C初阶 &#x1f3af;长路漫漫浩浩&#xff0c;万事皆有期待 上一篇博客&#xff1a;【C初阶】…

MySQL数据库学习笔记之存储引擎

存储引擎 MySQL体系结构 连接层 最上层是一些客户端和连接服务&#xff0c;主要完成一些类似于连接处理、授权认证、以及相关的安全方案。服务器也会为安全接入的每个客户端验证它所具有的操作权限。 服务层 第二层架构主要完成大多数的核心服务功能&#xff0c;如SQL接口&am…

【Linux网络】部署YUM仓库及NFS服务

部署YUM仓库及NSF服务 一、YUM仓库1.1、YUM仓库概述1.2准备安装来源1.3在软件仓库加载非官方RPM包组1.4yum与apt 二、配置yam源与制作索引表2.1配置FTP源2.2配置国内在线yum源2.3在线源与本地源同时使用2.4建立软件包索引关系表的三种方法 三、nfs共享存储服务3.1安装软件&…