经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » Java相关 » Spring Boot » 查看文章
springboot实现分页功能的完整代码
来源:jb51  时间:2023/4/17 9:15:56  对本文有异议

1.分页功能的作用

分页功能作为各类网站和系统不可或缺的部分(例如百度搜索结果的分页等),当一个页面数据量大的时候分页作用就体现出来的,其作用有以下5个。

(1)减少系统资源的消耗

(2)提高数据库的查询性能

(3)提升页面的访问速度

(4)符合用户的浏览习惯

(5)适配页面的排版

2.建立测试数据库

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

  1. DROP TABLE IF EXISTS tb_user;
  2.  
  3. CREATE TABLE tb_user (
  4. id int(11) NOT NULL AUTO_INCREMENT COMMENT '主键id',
  5. name varchar(100) NOT NULL DEFAULT '' COMMENT '登录名',
  6. password varchar(100) NOT NULL DEFAULT '' COMMENT '密码',
  7. PRIMARY KEY (id) USING BTREE
  8. ) ENGINE = InnoDB CHARACTER SET = utf8;
  9.  
  10. insert into tb_user (id,name,password)
  11. value (1,'C','123456'),
  12. (2,'C++','123456'),
  13. (3,'Java','123456'),
  14. (4,'Python','123456'),
  15. (5,'R','123456'),
  16. (6,'C#','123456');
  17.  
  18. insert into tb_user (id,name,password) value (7,'test1','123456');
  19. insert into tb_user (id,name,password) value (8,'test2','123456');
  20. insert into tb_user (id,name,password) value (9,'test3','123456');
  21. insert into tb_user (id,name,password) value (10,'test4','123456');
  22. insert into tb_user (id,name,password) value (11,'test5','123456');
  23. insert into tb_user (id,name,password) value (12,'test6','123456');
  24. insert into tb_user (id,name,password) value (13,'test7','123456');
  25. insert into tb_user (id,name,password) value (14,'test8','123456');
  26. insert into tb_user (id,name,password) value (15,'test9','123456');
  27. insert into tb_user (id,name,password) value (16,'test10','123456');
  28. insert into tb_user (id,name,password) value (17,'test11','123456');
  29. insert into tb_user (id,name,password) value (18,'test12','123456');
  30. insert into tb_user (id,name,password) value (19,'test13','123456');
  31. insert into tb_user (id,name,password) value (20,'test14','123456');
  32. insert into tb_user (id,name,password) value (21,'test15','123456');
  33. insert into tb_user (id,name,password) value (22,'test16','123456');
  34. insert into tb_user (id,name,password) value (23,'test17','123456');
  35. insert into tb_user (id,name,password) value (24,'test18','123456');
  36. insert into tb_user (id,name,password) value (25,'test19','123456');
  37. insert into tb_user (id,name,password) value (26,'test20','123456');
  38. insert into tb_user (id,name,password) value (27,'test21','123456');
  39. insert into tb_user (id,name,password) value (28,'test22','123456');
  40. insert into tb_user (id,name,password) value (29,'test23','123456');
  41. insert into tb_user (id,name,password) value (30,'test24','123456');
  42. insert into tb_user (id,name,password) value (31,'test25','123456');
  43. insert into tb_user (id,name,password) value (32,'test26','123456');
  44. insert into tb_user (id,name,password) value (33,'test27','123456');
  45. insert into tb_user (id,name,password) value (34,'test28','123456');
  46. insert into tb_user (id,name,password) value (35,'test29','123456');
  47. insert into tb_user (id,name,password) value (36,'test30','123456');
  48. insert into tb_user (id,name,password) value (37,'test31','123456');
  49. insert into tb_user (id,name,password) value (38,'test32','123456');
  50. insert into tb_user (id,name,password) value (39,'test33','123456');
  51. insert into tb_user (id,name,password) value (40,'test34','123456');
  52. insert into tb_user (id,name,password) value (41,'test35','123456');
  53. insert into tb_user (id,name,password) value (42,'test36','123456');
  54. insert into tb_user (id,name,password) value (43,'test37','123456');
  55. insert into tb_user (id,name,password) value (44,'test38','123456');
  56. insert into tb_user (id,name,password) value (45,'test39','123456');
  57. insert into tb_user (id,name,password) value (46,'test40','123456');
  58. insert into tb_user (id,name,password) value (47,'test41','123456');
  59. insert into tb_user (id,name,password) value (48,'test42','123456');
  60. insert into tb_user (id,name,password) value (49,'test43','123456');
  61. insert into tb_user (id,name,password) value (50,'test44','123456');
  62. insert into tb_user (id,name,password) value (51,'test45','123456');

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

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

  1. package ltd.newbee.mall.entity;
  2.  
  3. public class User {
  4. private Integer id;
  5. private String name;
  6. private String password;
  7.  
  8. public Integer getId() {
  9. return id;
  10. }
  11.  
  12. public void setId(Integer id) {
  13. this.id = id;
  14. }
  15.  
  16. public String getName() {
  17. return name;
  18. }
  19.  
  20. public void setName(String name) {
  21. this.name = name;
  22. }
  23.  
  24. public String getPassword() {
  25. return password;
  26. }
  27.  
  28. public void setPassword(String password) {
  29. this.password = password;
  30. }
  31. }

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

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

  1. package ltd.newbee.mall.util;
  2.  
  3. import java.util.List;
  4.  
  5. /**
  6. * 分页工具类
  7. */
  8. public class PageResult {
  9. //总记录数
  10. private int totalCount;
  11. //每页记录数
  12. private int pageSize;
  13. //总页数
  14. private int totalPage;
  15. //当前页数
  16. private int currPage;
  17. //列表数据
  18. private List<?> list;
  19.  
  20. /**
  21. *
  22. * @param totalCount 总记录数
  23. * @param pageSize 每页记录数
  24. * @param currPage 当前页数
  25. * @param list 列表数据
  26. */
  27. public PageResult(int totalCount, int pageSize, int currPage, List<?> list) {
  28. this.totalCount = totalCount;
  29. this.pageSize = pageSize;
  30. this.currPage = currPage;
  31. this.list = list;
  32. this.totalPage = (int) Math.ceil((double) totalCount / pageSize);
  33. }
  34.  
  35. public int getTotalCount() {
  36. return totalCount;
  37. }
  38.  
  39. public void setTotalCount(int totalCount) {
  40. this.totalCount = totalCount;
  41. }
  42.  
  43. public int getPageSize() {
  44. return pageSize;
  45. }
  46.  
  47. public void setPageSize(int pageSize) {
  48. this.pageSize = pageSize;
  49. }
  50.  
  51. public int getTotalPage() {
  52. return totalPage;
  53. }
  54.  
  55. public void setTotalPage(int totalPage) {
  56. this.totalPage = totalPage;
  57. }
  58.  
  59. public int getCurrPage() {
  60. return currPage;
  61. }
  62.  
  63. public void setCurrPage(int currPage) {
  64. this.currPage = currPage;
  65. }
  66.  
  67. public List<?> getList() {
  68. return list;
  69. }
  70.  
  71. public void setList(List<?> list) {
  72. this.list = list;
  73. }
  74. }

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

4.1数据层

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

  1. /**
  2. * 返回分页数据列表
  3. *
  4. * @param pageUtil
  5. * @return
  6. */
  7. List<User> findUsers(PageQueryUtil pageUtil);
  8.  
  9. /**
  10. * 返回数据总数
  11. *
  12. * @param pageUtil
  13. * @return
  14. */
  15. int getTotalUser(PageQueryUtil pageUtil);

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

  1. <!--分页-->
  2. <!--查询用户列表-->
  3. <select id="findUsers" parameterType="Map" resultMap="UserResult">
  4. select id,name,password from tb_user
  5. order by id desc
  6. <if test="start!=null and limit!=null">
  7. limit #{start}.#{limit}
  8. </if>
  9. </select>
  10. <!--查询用户总数-->
  11. <select id="getTotalUser" parameterType="Map" resultType="int">
  12. select count(*) from tb_user
  13. </select>

4.2业务层

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

  1. import ltd.newbee.mall.dao.UserDao;
  2. import ltd.newbee.mall.entity.User;
  3. import ltd.newbee.mall.util.PageResult;
  4. import ltd.newbee.mall.util.PageQueryUtil;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.stereotype.Service;
  7.  
  8. import java.util.List;
  9.  
  10. @Service
  11. public class UserService {
  12.  
  13. @Autowired
  14. private UserDao userDao;
  15.  
  16. public PageResult getUserPage(PageQueryUtil pageUtil){
  17. //当前页面中的数据列表
  18. List<User> users = userDao.findUsers(pageUtil);
  19. //数据总条数,用于计算分页数据
  20. int total = userDao.getTotalUser(pageUtil);
  21. //分页信息封装
  22. PageResult pageResult = new PageResult(users,total,pageUtil.getLimit(),pageUtil.getPage());
  23. return pageResult;
  24. }
  25. }

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

4.3控制层

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

  1. @RestController
  2. @RequestMapping("users")
  3. public class PageTestController {
  4.  
  5. @Autowired
  6. private UserService userService;
  7.  
  8. //分页功能测试
  9. @RequestMapping(value = "/list",method = RequestMethod.GET)
  10. public Result list(@RequestParam Map<String,Object> params){
  11. Result result = new Result();
  12. if (StringUtils.isEmpty(params.get("page"))||StringUtils.isEmpty(params.get("limit"))){
  13. //返回错误码
  14. result.setResultCode(500);
  15. //错误信息
  16. result.setMessage("参数异常!");
  17. return result;
  18. }
  19. //封装查询参数
  20. PageQueryUtil queryParamList = new PageQueryUtil(params);
  21. //查询并封装分页结果集
  22. PageResult userPage = userService.getUserPage(queryParamList);
  23. //返回成功码
  24. result.setResultCode(200);
  25. result.setMessage("查询成功");
  26. //返回分页数据
  27. result.setData(userPage);
  28. return result;
  29. }
  30. }

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

5.jqGrid分页插件

jqGrid是一个用来显示网格数据的jQuery插件。开发人员通过使用jqGrid可以轻松实现前端页面与后台数据的Ajax异步通信并实现分页功能。同时,jqGrid是一款代码开源的分页插件,源码也一直处于迭代更新的状态中。

下载地址:jqGrid

下载jqGrid后解压文件,将解压的文件直接拖进项目的static目录下

以下是jqGrid实现分页的步骤:

首先,在前端页面代码中引入jqGrid分页插件所需的源文件,代码如下所示:

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

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

  1. <!--jqGrid必要DOM,用于创建表格展示列表数据-->
  2. <table id="jqGrid" class="table table-bordered"></table>
  3.  
  4. <!--jqGrid必要DOM,分页信息区域-->
  5. <div id="jqGridPager"></div>

最后,调用jqGrid分页插件的jqGrid()方法渲染分页展示区域,代码如下所示:

请添加图片描述

请添加图片描述

jqGrid()方法中的参数及含义如图所示。

请添加图片描述

jqGrid前端页面测试:

在resources/static目中新建jqgrid-page-test.html文件,代码如下所示:

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

jqGrid初始化

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

  1. $(function () {
  2. $("#jqGrid").jqGrid({
  3. url: 'users/list',
  4. datatype: "json",
  5. colModel: [
  6. {label: 'id',name: 'id', index: 'id', width: 50, hidden: true,key:true},
  7. {label: '登录名',name: 'name',index: 'name', sortable: false, width: 80},
  8. {label: '密码字段',name: 'password',index: 'password', sortable: false, width: 80}
  9. ],
  10. height: 485,
  11. rowNum: 10,
  12. rowList: [10,30,50],
  13. styleUI: 'Bootstrap',
  14. loadtext: '信息读取中...',
  15. rownumbers: true,
  16. rownumWidth: 35,
  17. autowidth: true,
  18. multiselect: true,
  19. pager: "#jqGridPager",
  20. jsonReader:{
  21. root: "data.list",
  22. page: "data.currPage",
  23. total: "data.totalCount"
  24. },
  25. prmNames:{
  26. page: "page",
  27. rows: "limit",
  28. order: "order"
  29. },
  30. gridComplete: function () {
  31. //隐藏grid底部滚动条
  32. $("#jqGrid").closest(".ui-jqgrid-bdiv").css({"overflow-x": "hidden"});
  33. }
  34. });
  35. $(window).resize(function () {
  36. $("jqGrid").setGridWidth($(".card-body").width());
  37. });
  38. });

总结

到此这篇关于springboot实现分页功能的文章就介绍到这了,更多相关springboot分页功能内容请搜索w3xue以前的文章或继续浏览下面的相关文章希望大家以后多多支持w3xue!

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号