Spring Boot整合Mybatis使用JQuery DataTables表格插件展示數據

寫這篇帖子的原因是自己最近完成了小型系統,使用到了DataTables表格插件,但在使用的過程中,遇到了一些大問題,且國內對相關插件的資料不多。致使自己進度緩慢,現對該插件及後端所使用的技術進行分享。

需求
  • 對數據進行分頁
  • 數據的格式化
  • 對指定數據的模糊查詢
所使用的技術

前端:JQuery DataTables、LayUI彈出層、BootStrap
後端:Spring Boot、thymeleaf模板引擎、Mybatis持久層框架

DataTable參數

  • DataTables插件需要向後端傳遞必要的3個值,分別是

    前三個參數是必須要傳遞的,由插件完成,後端獲取就可以了

    1. draw:一個響應的繪製計數器
    2. start:分頁參數的其中一個參數
    3. length:分頁參數的另一個參數
    4. 之後的多個參數可以是將要進行模糊查詢的數據
  • 後端向前端返回的值:

    下列字段是必須要傳遞的,當然還有其他的數據,具體請看官網介紹

    1. draw:這個數據由前端傳過來,後端不作處理,直接返回即可
    2. recordsFiltered:過濾後的數據總數
    3. recordsTotal:數據的總條數
    4. data:返回的json數據
對日誌功能進行分析
後端:

項目結構圖:
項目結構圖
* dao接口

@Repository
@Mapper
public interface SysLogInfoDao {
    // 分頁查詢數據
    List<SysLogInfo> listSysLogInfo(Map map);
    // 查詢總數量
    Integer getLogInfoCount(Map map);
}
  • mapping.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.project.sccl.dao.SysLogInfoDao">
    <!--查詢登錄日誌或者單點日誌-->
    <!--動態SQL實現數據的查詢-->
    <select id="listSysLogInfo" parameterType="java.util.Map" resultType="com.project.sccl.domain.SysLogInfo">
        SELECT *
        FROM
        (SELECT
        A.*,
        ROWNUM RN
        FROM
        (SELECT L.party_account,
        to_char(L.access_date,
        'YYYY-MM-DD HH24-MI-SS') AS access_date, to_char(L.response_date,'YYYY-MM-DD HH24-MI-SS') AS response_date,
        L.log_type,L.app_id,L.menu_id,L.menu_name,L.phone_info,L.phone_unique,L.error_msg from sys_log_info L
        <where>
            <if test="account != null and account.length > 0">
                L.party_account = #{account}
            </if>
            <if test='logtype.length > 0 and logtype == "2" '>
                and L.app_id = 'FF_LOGIN'
            </if>
            <if test='logtype.length > 0 and logtype == "1" '>
                and L.app_id != 'FF_LOGIN'
            </if>
            <if test="logdate != null and logdate.length > 0">
                and to_char(L.access_date, 'yyyy-mm-dd') = #{logdate}
            </if>
            <if test="starttime != null and starttime.length > 0 or endtime != null and endtime.length > 0">
                and L.access_date BETWEEN to_date(#{starttime}, 'yyyy-mm-dd HH24:MI') AND to_date(#{endtime},
                'yyyy-mm-dd HH24:MI')
            </if>
        </where>
        order by L.access_date desc
        ) A
        WHERE ROWNUM
        <![CDATA[<= (#{end})) TL
        WHERE RN >= #{start}
        ]]>
    </select>
    <!--查數量-->
    <select id="getLogInfoCount" parameterType="java.util.Map" resultType="java.lang.Integer">
        SELECT count(1)
        FROM sys_log_info
        <where>
            <if test="account != null and account.length > 0">
                party_account = #{account}
            </if>
            <if test='logtype.length > 0 and logtype == "2" '>
                and app_id = 'FF_LOGIN'
            </if>
            <if test='logtype.length > 0 and logtype == "1" '>
                and app_id != 'FF_LOGIN'
            </if>
            <if test="logdate != null and logdate.length > 0">
                and to_char(access_date, 'yyyy-mm-dd') = #{logdate}
            </if>
            <if test="starttime != null and starttime.length > 0 or endtime != null and endtime.length > 0">
                and access_date BETWEEN to_date(#{starttime}, 'yyyy-mm-dd HH24:MI') AND to_date(#{endtime},
                'yyyy-mm-dd HH24:MI')
            </if>
        </where>
    </select>
</mapper>
  • service接口
public interface SysLogInfoService {
    // 返回數據
    Paging<SysLogInfo> listLogInfo(String account,
                                   String logtype,
                                   String logdate,
                                   String starttime,
                                   String endtime,
                                   Integer start,
                                   Integer length,
                                   Integer draw);
}
  • service接口實現類
@Service
public class SysLogInfoServiceImpl implements SysLogInfoService {

    @Autowired
    private SysLogInfoDao sysLogInfoDao;

    @Override
    public Paging<SysLogInfo> listLogInfo(String account, String logtype, String logdate, String starttime, String endtime, Integer start, Integer length, Integer draw) {
        // 將參數放進map中
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> map1 = new HashMap<>();
        List<SysLogInfo> list = null;
        map.put("account", account);
        map.put("logtype", logtype);
        map.put("logdate", logdate);
        map.put("starttime", starttime.replace("T", " "));
        map.put("endtime", endtime.replace("T", " "));
        map.put("start", start + 1);
        map.put("end", start + length);

        map1.put("account", account);
        map1.put("logtype", logtype);
        map1.put("logdate", logdate);
        map1.put("starttime", starttime.replace("T", " "));
        map1.put("endtime", endtime.replace("T", " "));
        Integer count = null;
        try {
            list = sysLogInfoDao.listSysLogInfo(map);
            count = sysLogInfoDao.getLogInfoCount(map1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Paging paging = new Paging(start, length, count, draw);
        paging.setRecordsFiltered(count);
        paging.setData(list);
        return paging;
    }

}
  • Controller層
@Controller
@RequestMapping(value = "/sysLogInfoController")
public class SysLogInfoController {

    @Autowired
    private SysLogInfoService sysLogInfoService;

    /**
     * @param draw  datatable傳入參數,不作處理,返回即可
     * @param account   將要查詢的賬戶信息,支持模糊查詢
     * @param index 分頁查詢參數
     * @param size  分頁查詢參數
     * @param logtype   日誌類型,1:單點日誌;2.登錄日誌
     * @param logdate   登錄時間 YYYY-MM-DD
     * @param starttime    開始時間,YYYY-MM-DD HH24:MI
     * @param endtime   結束時間,YYYY-MM-DD HH24:MI
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/listloginfo")
    public Paging<SysLogInfo> logInfoPaging(Integer draw,
                                            @RequestParam(value = "account",required = false) String account,
                                            @RequestParam(value = "start",defaultValue = "1") Integer index,
                                            @RequestParam(value = "length",defaultValue = "10") Integer size,
                                            @RequestParam(value = "logtype",required = false) String logtype,
                                            @RequestParam(value = "logdate",required = false) String logdate,
                                            @RequestParam(value = "starttime",required = false) String starttime,
                                            @RequestParam(value = "endtime",required = false) String endtime) {
        Paging<SysLogInfo> paging = null;
        try {
            paging = sysLogInfoService.listLogInfo(account,logtype,logdate,starttime,endtime,index,size,draw);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return paging;
    }
   }
  • 結果:
{
    "draw": 1,
    "page": 0,
    "length": 5, // 一頁顯示的數據條數
    "recordsTotal": 44298,
    "pages": 8860, // 總頁數
    "start": 5,
    "start1": 1,
    "end": 5,
    // 獲取到的數據
    "data": [{
        "party_account": "***********",
        "access_date": "2018-07-03 16-48-28",
        "response_date": "2018-07-03 16-48-29",
        "log_type": null,
        "app_id": "******************",
        "menu_id": null,
        "menu_name": null,
        "phone_info": null,
        "phone_unique": "FEB6A67E1A66C804360A4F748AA175",
        "error_msg": "成功"
    }, {
        "party_account": "***********",
        "access_date": "2018-07-03 16-42-30",
        "response_date": "2018-07-03 16-42-30",
        "log_type": null,
        "app_id": "********************",
        "menu_id": null,
        "menu_name": null,
        "phone_info": null,
        "phone_unique": "B4DE97838E28B9EBB53839321A45EFE2",
        "error_msg": "成功"
    }, {
        "party_account": "***********",
        "access_date": "2018-07-03 16-42-27",
        "response_date": "2018-07-03 16-42-27",
        "log_type": null,
        "app_id": "FF_LOGIN",
        "menu_id": null,
        "menu_name": null,
        "phone_info": "AND",
        "phone_unique": "****************",
        "error_msg": null
    }, {
        "party_account": "***********",
        "access_date": "2018-07-03 16-40-55",
        "response_date": "2018-07-03 16-40-55",
        "log_type": null,
        "app_id": "***************",
        "menu_id": null,
        "menu_name": null,
        "phone_info": null,
        "phone_unique": "1F8C6EF7F3AA74B355E186D55759A02E",
        "error_msg": "成功"
    }, {
        "party_account": "***********",
        "access_date": "2018-07-03 16-40-48",
        "response_date": "2018-07-03 16-40-48",
        "log_type": null,
        "app_id": "******************",
        "menu_id": null,
        "menu_name": null,
        "phone_info": null,
        "phone_unique": "D0ACBD4838A0F06759DDE2C1852379A4",
        "error_msg": "成功"
    }],
    "recordsFiltered": 44298
}
前端

這裏寫圖片描述
* 前端代碼:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8"/>
    <title>查詢登錄和單點日誌</title>
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
    <!-- 上述3個meta標籤*必須*放在最前面,任何其他內容都*必須*跟隨其後! -->
    <title>Bootstrap 101 Template</title>
    <link th:href="@{/css/bootstrap.min.css}" rel="stylesheet"/>
    <link th:href="@{/css/jquery.dataTables.min.css}" rel="stylesheet"/>
    <!-- jQuery (Bootstrap 的所有 JavaScript 插件都依賴 jQuery,所以必須放在前邊) -->
    <script th:src="@{/js/jquery.min.js}"></script>
    <!-- 加載 Bootstrap 的所有 JavaScript 插件。你也可以根據需要只加載單個插件。 -->
    <script th:src="@{/js/bootstrap.min.js}"></script>
    <script th:src="@{/js/jquery.dataTables.min.js}"></script>
    <style type="text/css">
        .table > tbody > tr > td {
            text-align: center;
        }

        /* dataTables表頭居中 */
        .table > thead:first-child > tr:first-child > th {
            text-align: center;
        }
    </style>
</head>
<body>
<div class="container">
    <div class="row clearfix">
        <div class="col-md-12 column">
            <ul class="nav nav-pills">
                <li>
                    <a href="../">配置菜單應用</a>
                    <!--<a href="../sysMenuController/tomain">配置菜單應用</a>-->
                </li>
                <li>
                    <a href="../partyAppMenuController/listPartyAPPMenu">查詢個人菜單</a>
                </li>
                <li class="">
                    <a href="../sysLogInfoController/tolistSysLogInfo">查詢登陸和單點日誌</a>
                </li>
                <li class="">
                    <a href="../sysVersionController/tolistSysVersion">查詢和修改版本號</a>
                </li>
                <li class="">
                    <a href="../sjmhPartyAccountController/tolistsjmhPartyAccount">查詢用戶是否擁有手機門戶角色權限</a>
                </li>
            </ul>
            <hr/>
        </div>
    </div>
</div>
<div class="row clearfix">
    <div class="col-md-12 column">
        <p><span>員工賬號:</span><input type="text" id="account" placeholder="輸入員工賬號"/><span>日誌類型:&nbsp;&nbsp;</span><select
                id="logtype">
            <option value="">請選擇</option>
            <option value="1">單點日誌</option>
            <option value="2">登錄日誌</option>
        </select></p>
        <p><span>時間點:&nbsp;&nbsp;</span><input type="date" id="logdate"/></p>
        <p><span>開始時間:</span><input type="datetime-local" id="starttime"/>&nbsp;&nbsp;<span>截止時間:&nbsp;&nbsp;<input
                type="datetime-local" id="endtime"/></span></p>
        <button type="button" class="btn btn-default btn-primary" onclick="search()">搜索</button>
    </div>
</div>
<hr/>
<div class="row clearfix">
    <div class="col-md-12 column">
        <table id="table" class="table table-border table-hover table-bg table-sort cell-border" width="100%">
            <thead>
            <tr>
                <th>員工信息</th>
                <th>訪問時間</th>
                <th>響應時間</th>
                <th>日誌類型</th>
                <th>APP_ID</th>
                <th>菜單ID</th>
                <th>菜單名稱</th>
                <th>手機操作系統信息</th>
                <th>手機串號信息唯一標識</th>
                <th>異常信息</th>
            </tr>
            </thead>
            <thead></thead>
        </table>
    </div>
</div>
<script type="text/javascript" th:inline="javascript">
    // 點擊搜索按鈕進行數據的渲染
    function search() {
        $("#table").dataTable().fnDraw();
    }
    $(document).ready(function () {
        $("#table").DataTable({ //對錶格控件進行初始化
            ordering: false,  // 關閉排序
            searching: false,  // 關閉插件自帶的搜索,我們會自定義搜索
            serverSide: true,  //服務器模式
            Processing: true,  //是否顯示“處理中...”
            scrollX: true,  //水平方向的滾動條
            autoWidth : true,  // 自動寬度
            lengthMenu: [5, 10, 25, 50, 100],  // 分頁器的頁數
            ajax: {
                //指定數據源
                url: "../sysLogInfoController/listloginfo",
                type: "POST",
                // 這裏向後端傳遞查詢參數
                data: function (d) {
                    d.account = $("#account").val().trim();
                    d.logtype = $("#logtype").val().trim();
                    d.logdate = $("#logdate").val().trim();
                    d.starttime = $("#starttime").val().trim();
                    d.endtime = $("#endtime").val().trim();
                }
            },
            // 與<table>標籤中的<th>標籤內的字段對應
            columns: [{
                data: "party_account"
            }, {
                data: "access_date"
            }, {
                data: "response_date"
            }, {
                data: "log_type"
            }, {
                data: "app_id"
            }, {
                data: "menu_id"
            }, {
                data: "menu_name"
            }, {
                data: "phone_info"
            }, {
                data: "phone_unique"
            }, {
                data: "error_msg"
            }],
            // 語言
            language: {
                "sProcessing": "處理中...",
                "sLengthMenu": "顯示 _MENU_ 項結果",
                "sZeroRecords": "沒有匹配結果",
                "sInfo": "顯示第 _START_ 至 _END_ 項結果,共 _TOTAL_ 項",
                "sInfoEmpty": "顯示第 0 至 0 項結果,共 0 項",
                "sInfoFiltered": "(由 _MAX_ 項結果過濾)",
                "sInfoPostFix": "",
                "sSearch": "搜索:",
                "sUrl": "",
                "sEmptyTable": "表中數據爲空",
                "sLoadingRecords": "載入中...",
                "sInfoThousands": ",",
                "oPaginate": {
                    "sFirst": "首頁",
                    "sPrevious": "上頁",
                    "sNext": "下頁",
                    "sLast": "末頁"
                },
                "oAria": {
                    "sSortAscending": ": 以升序排列此列",
                    "sSortDescending": ": 以降序排列此列"
                }
            }
        });
    });
</script>
</body>
</html>
  • “顯示第 1 至 5 項結果”,由後端傳遞的recordsFiltered所實現,
  • “共 44,298 項”,由後端傳遞的recordsTotal所實現
結尾

在JQuery DataTables表格插件的功能上,我只使用的幾個筆記重要的功能,其他沒有明顯顯示的功能使用了默認值。具體參考DataTables官網,最好是英文官網。

查看項目源碼,請下載:https://download.csdn.net/download/lhc_makefunny/10517685

如文章中出現錯誤的描述,請在下方留言,我會及時改正。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章