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="external nofollow"  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" rel="external nofollow" />
    <link href="jqGrid-5.8.2/css/ui.jqgrid-bootstrap4.css" rel="external nofollow"  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());
    });
});

總結

到此這篇關於springboot實現分頁功能的文章就介紹到這瞭,更多相關springboot分頁功能內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: