Spring Boot整合Mybatis使用JQuery DataTables表格插件展示数据

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lhc_makefunny/article/details/80905890

写这篇帖子的原因是自己最近完成了小型系统,使用到了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

如文章中出现错误的描述,请在下方留言,我会及时改正。

猜你喜欢

转载自blog.csdn.net/lhc_makefunny/article/details/80905890