bootStrap-table服務器端后台分頁的使用,以及自定義搜索框的實現,前端代碼到數據查詢超詳細講解


關於分頁,之前一直純手寫js代碼來實現,最近又需要用到分頁,找了好多最終確定bootstrap-table,正好前端頁面用的是bootstrap。

首先下載BootStrap-table的js和CSS

下載地址:https://github.com/wenzhixin/bootstrap-table.git

下載完后解壓

把bootstrap-table.js、bootstrap-table-zh-CN.js、bootstrap-table.css復制到項目中

在jsp中引入js和css

<link href="../css/bootstrap-table.css" rel="stylesheet">
<script src="../js/bootstrap-table.js"></script>
<script src="../js/bootstrap-table-zh-CN.js"></script>

其他bootstrap相關文件和jQuery相關文件自行引入即可

先上一段jsp中代碼

<div class="panel">
    <div class="panel-body" style="padding-bottom: 1px;">
        <form class="form-horizontal">
            <div class="form-group">
                <div class="col-sm-3">
                    <!-- 自定義搜索框 -->
                    <input type="text" name="searchString" id="searchString_id" class="form-control" placeholder="請輸入卡號" onkeydown="javascript:if(event.keyCode==13) searchId();" />
                </div>
                <div class="col-sm-1">
                    <button type="button" class="btn btn-primary btn-w-m" id="queryBtn">
                        <span class="glyphicon glyphicon-search"></span> 搜索
                    </button>
                </div>
            </div>
        </form>
    </div>
</div>
<div class="ibox-content">
    <table id="myTable"></table>
</div>

 再看js代碼

$(document).ready(function () {
  //調用函數,初始化表格
    initTable();
  //當點擊查詢按鈕的時候執行,bootstrap-table前端分頁是不能使用搜索功能,所以可以提取出來自定義搜索。后台代碼,在后面給出
    $("#queryBtn").bind("click", initTable);
});
function initTable() {
    //先銷毀表格
    $('#myTable').bootstrapTable('destroy');
    $('#myTable').bootstrapTable({
        url: "showConsumeRecordlList",//請求后台的URL(*)
        method: 'get',
        dataType: "json",
        dataField: 'rows',
        striped: true,//設置為 true 會有隔行變色效果
        undefinedText: "空",//當數據為 undefined 時顯示的字符
        pagination: true, //設置為 true 會在表格底部顯示分頁條。
        showToggle: "true",//是否顯示 切換試圖(table/card)按鈕
        showColumns: "true",//是否顯示 內容列下拉框
        pageNumber: 1,//初始化加載第一頁,默認第一頁
        pageSize: 10,//每頁的記錄行數(*)
        pageList: [10, 20, 30, 40],//可供選擇的每頁的行數(*),當記錄條數大於最小可選擇條數時才會出現
        paginationPreText: '上一頁',
        paginationNextText: '下一頁',
        search: false, //是否顯示表格搜索,bootstrap-table服務器分頁不能使用搜索功能,可以自定義搜索框,上面jsp中已經給出,操作方法也已經給出
        striped : true,//隔行變色
        showColumns: false,//是否顯示 內容列下拉框
        showToggle: false, //是否顯示詳細視圖和列表視圖的切換按鈕
        clickToSelect: true,  //是否啟用點擊選中行
        data_local: "zh-US",//表格漢化
        sidePagination: "server", //服務端處理分頁
        queryParamsType : "limit",//設置為 ‘limit’ 則會發送符合 RESTFul 格式的參數.
        queryParams: function (params) {//自定義參數,這里的參數是傳給后台的,我這是是分頁用的
//            請求服務器數據時,你可以通過重寫參數的方式添加一些額外的參數,例如 toolbar 中的參數 如果
//       queryParamsType = 'limit' ,返回參數必須包含
limit, offset, search, sort, order
// queryParamsType = 'undefined', 返回參數必須包含:
pageSize, pageNumber, searchText, sortName, sortOrder. // 返回false將會終止請求。 return {//這里的params是table提供的 offset: params.offset,//從數據庫第幾條記錄開始 limit: params.limit,//找多少條 memberId: $("#searchString_id").val() //這個就是搜索框中的內容,可以自動傳到后台,搜索實現在xml中體現 }; }, responseHandler: function (res) {
      //如果后台返回的json格式不是{rows:[{...},{...}],total:100},可以在這塊處理成這樣的格式

      return res; }, columns: [{ field: 'xuhao', title: '序號', formatter: idFormatter }, { field: 'memberId', title: '會員卡號', }, { field: 'name', title: '會員姓名' }, { field: 'payTime', title: '繳費時間', formatter: timeFormatter }, { field: 'payNo', title: '繳費單號' }, { field: 'payEntry', title: '收款條目', formatter: payEntryFormatter }, { field: 'cardType', title: '卡種', formatter: cardTypeFormatter }, { field: 'payMoney', title: '繳費金額' }, { field: 'operate', title: '繳費詳情', formatter: operateFormatter } ], onLoadSuccess: function () { }, onLoadError: function () { showTips("數據加載失敗!"); } }); } function idFormatter(value, row, index){ return index+1; } function timeFormatter(value, row, index) { if (value != null) { var date = new Date(dateTime); var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1; var currentDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate(); var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours(); var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes(); var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds(); return date.getFullYear() + "-" + month + "-" + currentDate + " " + hours + ":" + minutes + ":" + seconds; } } function payEntryFormatter(value, row, index){ switch(row.payEntry){ case '1': value='繳費種類1'; break; case '2': value='繳費種類2'; break; case '3': value='繳費種類3'; break; default: value='其他'; break; } return value; } function cardTypeFormatter(value, row, index) { switch(row.cardType){ case '1': value='卡種1'; break; case '2': value='卡種2'; break; case '3': value='卡種3'; break; default: value='其他'; break; } return value; } function operateFormatter(value, row, index) { return '<button type="button" onClick="showConsumeRecord('+id+')" class="btn btn-xs btn-primary" data-toggle="modal" data-target="#consumeModal">查看</button>'; }

前段准備就緒,開始服務器代碼

准備分頁實體

package com.gym.utils;

public class Page {
    // 每頁顯示數量
    private int limit;
    // 頁碼
    private int page;
    // sql語句起始索引
    private int offset;
    // setter and getter....
}

准備展示實體

import java.util.Date;
import com.gym.utils.Page;

public class ConsumeRecord extends Page {
    private Integer id;
    private Integer memberId;
    private String months;
    private Long payMoney;
    private Date payTime;
    private String payStatus;
    private String payEntry;
    private String remark;
    private String name;
    private String cardType;
    private Date endTime;
    private Date registerTime;
    private String payNo;
    // setter and getter...
}

再來一個分頁幫助類

import java.util.ArrayList;
import java.util.List;

public class PageHelper<T> {
    // 注意:這兩個屬性名稱不能改變,是定死的
    // 實體類集合
    private List<T> rows = new ArrayList<T>();
    // 數據總條數
    private int total;
    // setter and getter...
}

編寫Controller

    /**
     * 展示繳費詳情列表
     * 
     * @param modelMap
     * @return
     */
    @RequestMapping("/showConsumeRecordlListA")
    @ResponseBody
    public String showConsumeRecordlListA(ConsumeRecord consumeRecord, HttpServletRequest request) {
        PageHelper<ConsumeRecord> pageHelper = new PageHelper<ConsumeRecord>();
        // 統計總記錄數
        Integer total = consumerRecordService.getTotal(consumeRecord);
        pageHelper.setTotal(total);

        // 查詢當前頁實體對象
        List<ConsumeRecord> list = consumerRecordService.getConsumerRecordListPage(consumeRecord);
        pageHelper.setRows(list);

        return new GsonBuilder().serializeNulls().create().toJson(pageHelper);
    }

經過Service層,這塊就不粘貼了,直接到達mapper

import java.util.List;
import com.entity.ConsumeRecord;

public interface ConsumeRecordMapper {
    ...
    ...
    /**
     * 獲取消費記錄條數
     * 
     * @param consumeRecord
     * @return
     */
    Integer getTotal(ConsumeRecord consumeRecord);

    /**
     * 分頁查詢消費記錄集合
     * 
     * @param consumeRecord
     * @return
     */
    List<ConsumeRecord> getConsumerRecordListPage(ConsumeRecord consumeRecord);
}

然后mapper.xml

<!-- 查詢符合條件的繳費總條數 -->
    <select id="getTotal" parameterType="com.entity.ConsumeRecord" resultType="int">
        SELECT count(1) FROM consume_record where 1=1  
        <if test="memberId != null and memberId != ''">
            and member_id=#{memberId}
          </if> 
    </select>
    <!-- 查詢符合條件的繳費信息集合 -->
    <select id="getConsumerRecordListPage" parameterType="com.entity.ConsumeRecord" resultMap="BaseResultMap">
        SELECT * FROM consume_record  where 1=1  
        <if test="memberId != null and memberId != ''">
            and member_id=#{memberId}
          </if> 
          ORDER BY pay_time DESC
        LIMIT #{offset},#{limit}
    </select>

這是bootstrap-table官方文檔,主要解釋參數的意思,可根據文檔按照自己的需求更改代碼

http://bootstrap-table.wenzhixin.net.cn/zh-cn/documentation/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM