基於springBoot+DataTables插件的分頁實現

這個插件我感覺挺好用,配置也簡單,自帶條件對象,下面我就以我的項目代碼來說明:

首先重要的兩個依賴:

<script  src="../../hplus/plugins/hjk/plugins/DataTables/js/jquery.dataTables.js"></script>
<link href="../../hplus/plugins/hjk/plugins/DataTables/css/data-table.css" rel="stylesheet">

接下來是前臺代碼:


<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">


<!-- Mirrored from www.zi-han.net/theme/hplus/weixinportal.html by HTTrack Website Copier/3.x [XR&CO'2014], Wed, 20 Jan 2016 14:19:58 GMT -->
<head>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>微信菜單</title>
    <meta name="keywords" content="H+後臺主題,後臺bootstrap框架,會員中心主題,後臺HTML,響應式後臺">
    <meta name="description" content="H+是一個完全響應式,基於Bootstrap3最新版本開發的扁平化主題,她採用了主流的左右兩欄式佈局,使用了Html5+CSS3等現代技術">
    <link rel="shortcut icon" href="../favicon.ico">
    <link href="../../hplus/css/bootstrap.min14ed.css?v=3.0.3" rel="stylesheet">
    <link href="../../hplus/css/font-awesome.min93e3.css?v=4.4.0" rel="stylesheet">
    <link href="../../hplus/css/animate.min.css" rel="stylesheet">
    <link href="../../hplus/css/style.min862f.css?v=4.1.0" rel="stylesheet">
    <link href="../../hplus/plugins/hjk/plugins/jquery-confirm/jquery-confirm.min.css" rel="stylesheet"/>
    <link href="../../hplus/plugins/hjk/css/bootstrap-treeview.css" rel="stylesheet">
    <link href="../../hplus/plugins/hjk/plugins/gritter/css/jquery.gritter.css" rel="stylesheet">
    <link href="../../hplus/plugins/hjk/plugins/bootstrap-select-1.12.1/css/bootstrap-select.min.css" rel="stylesheet">
    <link href="../../hplus/plugins/hjk/plugins/DataTables/css/data-table.css" rel="stylesheet">
</head>
<!--解決表格標題內容居中問題-->
<style>
    table tr td{
        text-align: center!important;
    }
    table tr th{
        text-align: center!important;
    }
</style>
<body class="gray-bg">

<form class="form-horizontal form-bordered" data-parsley-validate="true" name="bgPicture-form" id="bgPicture-form">
    <div class="modal-body">
        <div class="form-group">
            <div class="row">
                <div class="col-sm-12" >
                    <div class="ibox ">
                        <div class="ibox-content">
                            <form class="form-horizontal form-bordered" id="queryForm">
                                <div class="form-group">
                                    <div class="col-md-4 ">
                                        <div class="input-group">
                                            <span class="input-group-addon">提問內容:</span>
                                            <input id="description" type="text" class="form-control">
                                        </div>
                                        <div class="input-group">
                                            <span class="input-group-addon">提問人:</span>
                                            <input id="username" type="text" class="form-control">
                                        </div>
                                    </div>
                                    <div class="col-md-4 ">
                                        <div class="input-group">
                                            <button type="button" class="btn btn-primary m-r-5 m-b-5" id="query">查詢</button>
                                        </div>
                                    </div>
                                    <div class="col-md-4 ">
                                        <div class="input-group">
                                            <button type="button" id="submitContentBtn" class="btn btn-sm btn-primary">查看詳情</button>
                                        </div>
                                    </div>
                                </div>
                            </form>

                            <hr>
                            <div class="table-responsive">
                                <table id="data-table" class="table table-striped table-bordered display" cellspacing="0" width="100%">
                                    <thead>
                                    <tr>
                                        <th>
                                        <input type="checkbox" class="checkall" />
                                        </th>
                                        <th >ID</th>
                                        <th >提問人</th>
                                        <th >提問內容</th>
                                        <th >提問時間</th>
                                        <th >圖片數量</th>
                                        <th >回覆人</th>
                                    </tr>
                                    </thead>
                                    <tbody id="tbodyId">
                                    <tr>
                                        <td>0</td>
                                        <td>0</td>
                                        <td>0</td>
                                        <td>0</td>
                                        <td>0</td>
                                        <td>0</td>
                                        <td>0</td>
                                    </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</form>

<script  src="../../hplus/js/jquery.min.js?v=2.1.4"></script>
<script  src="../../hplus/js/content.min.js?v=1.0.0"></script>
<script  src="../../hplus/plugins/hjk/js/bootstrap-treeview.js"></script>
<script  src="../../hplus/plugins/hjk/plugins/gritter/js/jquery.gritter.js"></script>
<script  src="../../hplus/plugins/hjk/plugins/parsley/dist/parsley.js"></script>
<script  src="../../hplus/plugins/hjk/plugins/jquery/jquery.form.js"></script>
<script  src="../../hplus/plugins/hjk/plugins/jquery-confirm/jquery-confirm.min.js"></script>
<script  src="../../hplus/plugins/hjk/plugins/bootstrap-select-1.12.1/js/bootstrap-select.min.js"></script>
<script  src="../../hplus/plugins/hjk/plugins/bootstrap-select-1.12.1/js/i18n/defaults-zh_CN.min.js"></script>
<script  src="../../hplus/plugins/hjk/plugins/switchery/switchery.min.js"></script>
<script  src="../../hplus/plugins/hjk/plugins/DataTables/js/jquery.dataTables.js"></script>
<script  src="../../hplus/js/bootstrap.min.js?v=3.3.6"></script>

<script>
    $(document).ready(function () {
        //初始化按鈕綁定事件
        $("#query").click(function(){
            t.ajax.reload();
        });

        var t=null;
        t=$("#data-table").DataTable( {
            "processing":true,
            "serverSide":true,
            "pageLength": 10,  //首次加載的數據條數
            "ordering": false, //排序操作在服務端進行,所以可以關了。
            "paging":true,
            "pagingType": "full_numbers",
            "autoWidth": false,
            "searching": false,//禁用搜索
            "columns": [
                //序號
                {
                    "sClass": "text-center",
                    "data": "id",
                    "render": function (data, type, full, meta) {
                        return '<input type="checkbox"  class="checkchild"  value="' + data + '" />';
                    },
                    "bSortable": false
                },
                //ID
                {"data": "id"},
                //提問人
                { "data": "openid" },
                //提問詳情
                { "data": "description"},
                //提問時間
                { "data": "gmtCreate" },
                //圖片數
                { "data": "imageNumber" },
                //回覆人
                { "data": "replyName" }
            ],
            "ajax":{
                type: "get",
                url:'/quiz/service',
                data: function (d) {
                    var param = {};
                    param.draw = d.draw;
                    param.start = d.start;
                    param.length = d.length;
                    //獲得提問人搜索條件
                    var username = $("#username").val();
                    //給請求添加條件
                    if(username!=undefined){
                        param.username = username;
                    }

                    //獲得提問人搜索條件
                    var description = $("#description").val();
                    //給請求添加條件
                    if(description!=undefined){
                        param.description = description;
                    }
                    return param;//自定義需要傳遞的參數。
                }
            }
        } );

    });

    /*查看內容詳情*/
    $("#submitContentBtn").click(function () {
        //獲取選中的某一個checkbox的值
        if ($(".checkchild:checked").length > 1){
            $.alert({
                title: '提示',
                content: '一次只能選擇一條數據!',
            });
            return;
        }else if($(".checkchild:checked").length == 0){
            $.alert({
                title: '提示',
                content: '請選擇一條數據!',
            });
            return;
        }

        //獲取ID
        var id = $(".checkchild:checked").val();
        //ID存入localStorage會話中
        localStorage.setItem("id",id)
        //加載詳情頁
        window.location.href="/quiz/details";

    });

</script>
</body>

</html>
分頁封裝實體類:
package com.zenithink.spp.cms.util;

import java.util.List;

public class Datatables<T> {  
 //每頁顯示集合
    private List<T> data;//LIST(結果集)
 //總記錄數
    private long recordsTotal;

    private long recordsFiltered;
 //請求次數
    private long draw;

    public Datatables() {  

    }

    public long getDraw() {
        return draw;
    }

    public void setDraw(long draw) {
        this.draw = draw;
    }

    public List<T> getData() {
        return data;
    }

    public void setData(List<T> data) {
        this.data = data;
    }

    public long getRecordsTotal() {
        return recordsTotal;
    }

    public void setRecordsTotal(long recordsTotal) {
        this.recordsTotal = recordsTotal;
        this.recordsFiltered = recordsTotal;
    }

    public long getRecordsFiltered() {
        return recordsFiltered;
    }

    public void setRecordsFiltered(long recordsFiltered) {
        this.recordsFiltered = recordsFiltered;
    }  
} 
接下來是後臺代碼:
/**
 * 提問模塊分頁
 * @param draw 請求次數
 * @param start 起始數
 * @param length 每頁顯示數
 * @param username 條件查詢暱稱
 * @param description 條件查詢內容
 * @param request
 * @return
 */
@RequestMapping(value = "/service",method = RequestMethod.GET)
@ResponseBody
public Datatables<Map<String,Object>> quizPage2(Integer draw , Integer start, Integer length, String username, String description, HttpServletRequest request){

    //記錄總條數
    int total=0;
    //總記錄數
    List<Map<String,Object>> rowsList=new ArrayList<>();
    try {
        //若接收到的提問人不爲空
        if(username!=null&&!username.equals("")){

            //創建條件查詢對象
            Wrapper<WeixinUser> wrapper = new EntityWrapper<WeixinUser>();
            //添加查詢條件
            wrapper.like("nickname", username);

            //獲得模糊查詢到的用戶集合
            List<WeixinUser> Userlist= weixinUserService.selectList(wrapper);
            //創建接收用戶openid的集合
            List<String> openidList= new  ArrayList<String>();

            if (Userlist != null && Userlist.size() != 0) {
                //遍歷獲得openid並添加到集合中
                for (WeixinUser weixinUser : Userlist) {
                    openidList.add(weixinUser.getOpenid());
                }
            }

            //遍歷openid集合進行條件添加
            for (String s : openidList) {
                if(openidList!=null&&openidList.size()!=0){
                    //創建提問條件對象
                    Wrapper<QuestionInfo> ew=new EntityWrapper<QuestionInfo>();
                    //添加條件
                    ew.where("openid={0}",s);

                    //判斷接收到的當前頁和每頁顯示的集合數是否合法
                    if(length>=1){
                        //根據起始數得到當前頁
                        start=(start==0)?1:(start/length + 1);

                        //mybatis 分頁實體設置當前頁和每頁顯示數
                        Page<QuestionInfo> page=new Page<QuestionInfo>(start,length);

                        //查詢條件
                        ew.where("del_flag={0}", 1);

                        //若接收到的內容不爲空進行模糊查詢
                        if(description!=null&&!description.equals("")){
                            //添加模糊查詢內容
                            ew.like("description",description);
                        }

                        //根據創建時間進行排序
                        ew.orderBy("gmt_create",false);

                        //根據分頁條件查詢
                        Page<Map<String, Object>> mapPage = questionInfoService.selectMapsPage(page, ew);

                        //獲得總條數並進行累加
                        total+=mapPage.getTotal();
                        //獲得查詢的提問對象集合
                        List<Map<String,Object>> list=mapPage.getRecords();

                        if(list!=null&&list.size()!=0){
                            //遍歷集合
                            for (Map<String, Object> map : list) {
                                //獲得提問的id
                                Object o= map.get("id");
                                //id轉換成Integer類型
                                Integer question_id=Integer.parseInt(String.valueOf(o));
                                //創建條件查詢對象
                                Wrapper<PestImage> wr=new EntityWrapper<>();
                                //添加查詢條件
                                wr.where("question_id={0}",question_id);
                                //進行查詢獲得圖片的數量
                                int count=pestImageService.selectCount(wr);
                                //將圖片數量封裝到提問對象中
                                map.put("imageNumber",count);
                                //獲得用戶的ID
                                Object openid=map.get("openid");

                                //根據用戶ID查詢用戶
                                WeixinUser weixinUser = weixinUserService.selectById(String.valueOf(openid));
                                //將用戶名封裝到集合中
                                if(weixinUser!=null){
                                    map.put("openid",weixinUser.getNickname());
                                }
                                //解決頁面無值封裝警告
                                if(map.get("description")==null||map.get("description")==""){
                                    map.put("description","");
                                }
                                if(map.get("replyName")==null||map.get("replyName")==""){
                                    map.put("replyName","無回覆人");
                                }

                                //解決頁面顯示時間不能格式化問題
                                Object gmtCreate=map.get("gmtCreate");
                                map.put("gmtCreate",String.valueOf(gmtCreate));

                                rowsList.add(map);
                            }
                        }


                    }
                }
            }


        }else {
            if(length>=1){
                //根據起始數得到當前頁
                start=(start==0)?1:(start/length + 1);

                //mybatis 分頁實體設置當前頁和每頁顯示數
                Page<QuestionInfo> page=new Page<QuestionInfo>(start,length);

                Wrapper<QuestionInfo> ew=new EntityWrapper<QuestionInfo>();
                //查詢條件
                ew.where("del_flag={0}", 1);

                //若接收到的內容不爲空進行模糊查詢
                if(description!=null&&!description.equals("")){
                    //模糊查詢內容
                    ew.like("description",description);
                }
                //根據創建時間進行排序
                ew.orderBy("gmt_create",false);

                //根據分頁條件查詢
                Page<Map<String, Object>> mapPage = questionInfoService.selectMapsPage(page, ew);

                total+=mapPage.getTotal();
                //獲得查詢的提問對象集合
                List<Map<String,Object>> list=mapPage.getRecords();

                if(list!=null&&list.size()!=0){
                    //遍歷集合
                    for (Map<String, Object> map : list) {
                        //獲得提問的id
                        Object o= map.get("id");
                        //id轉換成Integer類型
                        Integer question_id=Integer.parseInt(String.valueOf(o));
                        //創建條件查詢對象
                        Wrapper<PestImage> wr=new EntityWrapper<>();
                        //添加查詢條件
                        wr.where("question_id={0}",question_id);
                        //進行查詢獲得圖片的數量
                        int count=pestImageService.selectCount(wr);
                        //將圖片數量封裝到提問對象中
                        map.put("imageNumber",count);
                        //獲得用戶的ID
                        Object openid=map.get("openid");

                        //根據用戶ID查詢用戶
                        WeixinUser weixinUser = weixinUserService.selectById(String.valueOf(openid));
                        //將用戶名封裝到集合中
                        if(weixinUser!=null){
                            map.put("openid",weixinUser.getNickname());
                        }

                        //解決頁面無值封裝警告
                        if(map.get("description")==null||map.get("description")==""){
                            map.put("description","");
                        }
                        if(map.get("replyName")==null||map.get("replyName")==""){
                            map.put("replyName","無回覆人");
                        }

                        //解決頁面顯示時間不能格式化問題
                        Object gmtCreate=map.get("gmtCreate");
                        map.put("gmtCreate",String.valueOf(gmtCreate));

                        rowsList.add(map);
                    }
                }


            }
        }

        //創建分頁封裝實體對象
        Datatables<Map<String,Object>> data = new Datatables<Map<String,Object>>();
        //封裝返回的分頁集合
        data.setData(rowsList);
        //封裝分頁插件的請求次數
        data.setDraw(draw);
        //封裝總記錄數
        data.setRecordsTotal(total);
        //將數據轉成JSON返回頁面
        return data;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }

}

下面是頁面效果:



發佈了42 篇原創文章 · 獲贊 28 · 訪問量 15萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章