1. 程式人生 > >第十一章 分頁及BaseController

第十一章 分頁及BaseController

  今天我們來講分頁,分頁前端有控制元件,後端使用pagehelper。

  從後端開始。先在entity裡建立base資料夾,並在裡面建立PageVo的類,裡面包含pageSize, pageNum, sortField, sortOrder四個屬性,並新增預設值。用來處理分頁

 1 public class PageVo {
 2     private Integer pageSize = 10;
 3     private Integer pageNum = 1;
 4     private String sortField = "id";
 5     private
String sortOrder = "desc"; 6 7 public Integer getPageSize() { 8 return pageSize; 9 } 10 11 public void setPageSize(Integer pageSize) { 12 this.pageSize = pageSize; 13 } 14 15 public Integer getPageNum() { 16 return pageNum; 17 } 18 19 public
void setPageNum(Integer pageNum) { 20 this.pageNum = pageNum; 21 } 22 23 public String getSortField() { 24 return sortField; 25 } 26 27 public void setSortField(String sortField) { 28 this.sortField = sortField; 29 } 30 31 public String getSortOrder() {
32 return sortOrder; 33 } 34 35 public void setSortOrder(String sortOrder) { 36 this.sortOrder = sortOrder; 37 } 38 39 public String getOrderBy() { 40 if (StringUtil.isEmpty(sortField)) { 41 return "id desc"; 42 } 43 return sortField + " " + sortOrder; 44 } 45 }
PageVo

  然後我們開啟UserController裡的,queryUser,新增接受引數PageVo, service中的介面及實現進行改造新增pageVo引數。

  Pom中新增對pagehelp的引用

<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper-spring-boot-starter</artifactId>
    <version>1.2.10</version>
</dependency>

 

  引用後,對PageVo進行修改,新增實現介面IPage,預設前臺不傳排序我們按id desc進行排序

public class PageVo implements IPage {

 

  在entity/base中建立PageResult物件,用來service層返回帶翻頁資訊的類,不直接使用PageInfo作為返回值是因為,裡面有我們用不到的屬性,減少無用資料的傳遞,還有就是可以以後我們需要擴充套件時方便我們擴充套件。直接使用PageInfo的話我們就沒辦法直接控制了。

 1 public class PageResult<T> {
 2     private List<T> list;
 3     private Integer pageNum;
 4     private Integer pageSize;
 5     private Long total;
 6     private Integer pages;
 7 
 8     public PageResult(PageInfo<T> pageInfo) {
 9         this.list = pageInfo.getList();
10         this.pageNum = pageInfo.getPageNum();
11         this.pageSize = pageInfo.getPageSize();
12         this.total = pageInfo.getTotal();
13         this.pages = pageInfo.getPages();
14     }
15      //get,set略
16 }

 

  在UserServiceImpl中,修改query如下。

 

1 @Override
2     public PageResult<User> query(QueryUser vo, PageVo pageVo) {
3         PageHelper.startPage(pageVo);
4         List<User> users = userMapper.select(vo);
5         PageInfo<User> pageInfo = new PageInfo<User>(users);
6         return new PageResult<>(pageInfo);
7     }

 

  然後,我們對返回的結果進行改造,初期還是使用map來做,不過建立一個BaseController用來處理所有的通用內容,以後獲取登陸資訊也在這裡處理。 

 1 public class BaseController {
 2 
 3     private static final String CODE_SUCCESS = "0";
 4     private static final String CODE_ERROR = "1001";
 5     private static final String CODE_AUTHER = "5001";
 6 
 7     public Map<String, Object> getResultMessage(PageResult result) {
 8         return getResultMessage(true, result.getList(), result.getPageInfo(), CODE_SUCCESS, "");
 9     }
10 
11     public Map<String, Object> getResultMessage(Object data) {
12         return getResultMessage(true, data, CODE_SUCCESS, "");
13     }
14 
15 
16     public Map<String, Object> getResultMessage(Boolean success, Object data, String code, String message) {
17         Map<String, Object> map = new HashMap<>();
18         map.put("success", success);
19         map.put("data", data);
20         map.put("message", message);
21         map.put("code", code);
22         return map;
23     }
24 
25     public Map<String, Object> getResultMessage(Boolean success, Object data, Object pageInfo, String code, String message) {
26         Map<String, Object> map = new HashMap<>();
27         map.put("success", success);
28         map.put("data", data);
29         map.put("page", pageInfo);
30         map.put("message", message);
31         map.put("code", code);
32         return map;
33     }
34 }
View Code

 

  中間還對PageResult進行改造,可以將分頁資訊單獨獲取出來 

1 public Map<String, Object> getPageInfo() {
2         Map<String, Object> map = new HashMap<>();
3         map.put("pageNum", pageNum);
4         map.put("pageSize", pageSize);
5         map.put("total", total);
6         map.put("pages", pages);
7         return map;
8     }

 

  這是返回json的格式。到目前為止後端處理完成

{
    "code": "0",
    "data": [{
        "id": 1,
        "username": "admin",
        "password": "",
        "salt": "",
        "realname": "admin",
        "sex": "1",
        "mail": "[email protected]",
        "phone": "1234567",
        "avatar": "",
        "remarks": "",
        "status": "0",
        "createTime": "2018-12-16 20:00:00",
        "editTime": "2018-12-16 20:00:00",
        "editor": 1,
        "editorName": "admin",
        "lastLoginTime": null,
        "lastLoginIp": null
    }],
    "success": true,
    "page": {
        "total": 1,
        "pages": 1,
        "pageSize": 10,
        "pageNum": 1
    },
    "message": ""
}
json結果

 

  我們再新增一條記錄,id為2的,再重新整理介面我們看到了user排到admin前面了,看控制檯的輸出也能看到分頁和排序了。

 

  檢視一下控制檯,也能看到查詢的sql上帶有分頁和排序資訊了

 

  接下來我們在前臺加分頁了。

  開啟user.vue,在table下面新增分頁控制元件的引用

     <el-row style="text-align: right">
            <el-pagination class="pagination"
                           background
                           @size-change="handleSizeChange"
                           @current-change="handleCurrentChange"
                           :current-page="pagination.currentPage"
                           :page-sizes="pagination.pageSizes"
                           :page-size="pagination.pageSize"
                           layout="total, sizes, prev, pager, next, jumper"
                           :total="pagination.total">
            </el-pagination>
        </el-row>

 

  在data裡,新增相關引數的引用。

 

    data() {
            return {
                loading: true,
                tableData: [],
                pagination: {
                    pageSizes: [1, 10, 20, 50],
                    currentPage: 1,
                    total: 0,
                    pageSize: 10,
                },
            }
        },

 

  新增兩個事件

            //改變時
            handleSizeChange(val) {
                this.pagination.pageSize = val;
                this.queryList();
            },
            //條目改變時
            handleCurrentChange(val) {
                this.pagination.currentPage = val;
                this.queryList();
            },        

 

  並在查詢結果時,對引數進行賦值。我們剛才在返回結果寫了success及message,所以我們調整一下返回結果的處理。

            Vue.axios.post(queryUrl, para)
                    .then(function (res) {
                        let result = res.data;
                        if (result.success) {
                            _this.tableData = result.data;
                            _this.pagination.total = result.page.total;
                        } else {
                            this.$message({
                                message: result.message,
                                type: "error",
                            });
                        }
                        _this.loading = false;
                    })
                    .catch(function (error) {
                        this.$message({
                            message: error,
                            type: "error",
                        })
                    });

 

  

  我們再加上一個查詢按鈕,用來測試一下每次查詢後顯示到第一頁的內容。

 

  完活,不算樣式的話。這個查詢終於做完了。

  下面是完整的user.vue程式碼

  1 <template>
  2     <div>
  3         <el-row>
  4             <el-button type="primary" size="small" id="search" @click="search">查詢</el-button>
  5         </el-row>
  6         <el-table :data="tableData" v-loading="loading" stripe style="width: 100%">
  7             <el-table-column prop="username" label="使用者名稱" width="180"/>
  8             <el-table-column prop="realname" label="姓名名" width="180"/>
  9             <el-table-column prop="sex" label="性別" width="100"/>
 10             <el-table-column prop="mail" label="郵箱" width="180"/>
 11             <el-table-column prop="phone" label="電話" width="180"/>
 12             <el-table-column prop="remark" label="備註" width="180"/>
 13             <el-table-column prop="status" label="狀態" width="180"/>
 14             <el-table-column prop="editorName" label="修改人" width="180"/>
 15             <el-table-column prop="editTime" label="修改時間" width="180"/>
 16         </el-table>
 17         <el-row style="text-align: right">
 18             <el-pagination class="pagination"
 19                            background
 20                            @size-change="handleSizeChange"
 21                            @current-change="handleCurrentChange"
 22                            :current-page="pagination.currentPage"
 23                            :page-sizes="pagination.pageSizes"
 24                            :page-size="pagination.pageSize"
 25                            layout="total, sizes, prev, pager, next, jumper"
 26                            :total="pagination.total">
 27             </el-pagination>
 28         </el-row>
 29     </div>
 30 </template>
 31 
 32 <script>
 33     import Vue from 'vue';
 34 
 35     export default {
 36         name: "userManage",
 37         data() {
 38             return {
 39                 loading: true,
 40                 tableData: [],
 41                 pagination: {
 42                     pageSizes: [1, 10, 20, 50],
 43                     currentPage: 1,
 44                     total: 0,
 45                     pageSize: 10,
 46                 },
 47             }
 48         },
 49         mounted: function () {
 50             this.queryList();
 51         },
 52         methods: {
 53             queryList: function () {
 54 
 55                 var _this = this;
 56                 var queryUrl = "/api/user/query";
 57                 let para = {
 58                     pageNum: this.pagination.currentPage,
 59                     pageSize: this.pagination.pageSize,
 60                 };
 61                 this.loading = true;
 62                 Vue.axios.post(queryUrl, para)
 63                     .then(function (res) {
 64                         let result = res.data;
 65                         if (result.success) {
 66                             _this.tableData = result.data;
 67                             _this.pagination.total = result.page.total;
 68                         } else {
 69                             this.$message({
 70                                 message: result.message,
 71                                 type: "error",
 72                             });
 73                         }
 74                         _this.loading = false;
 75                     })
 76                     .catch(function (error) {
 77                         this.$message({
 78                             message: error,
 79                             type: "error",
 80                         })
 81                     });
 82 
 83             },
 84             //改變時
 85             handleSizeChange(val) {
 86                 this.pagination.pageSize = val;
 87                 this.queryList();
 88             },
 89             //條目改變時
 90             handleCurrentChange(val) {
 91                 this.pagination.currentPage = val;
 92                 this.queryList();
 93             },
 94             search() {
 95                 this.pagination.currentPage = 1;
 96                 this.queryList();
 97             }
 98         }
 99     }
100 </script>
101 
102 <style scoped>
103 
104 </style>
user.vue