SpringBoot+Thymeleaf+DataTables实现数据的查询与显示

场景

效果:

DataTables官网:

http://www.datatables.club/

在你的项目中使用 DataTables,只需要引入三个文件即可,jQuery库,一个DT的核心js文件和一个DT的css文件。

这里使用的Thymeleaf模板,juqery是在foot中引用下面展示content部分。

实现

编写模板并引入js

首先在模板文件html中编写要显示的字段信息

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro"
     th:replace="layout/layout(title='收货单数据',cssPaths='/public/css/plugins/dataTables/datatables.min.css,/public/css/plugins/daterangepicker/daterangepicker-bs3.css,/public/css/plugins/jsTree/style.min.css',jsPaths='/public/js/plugins/dataTables/datatables.min.js,/public/js/plugins/dataTables/dataTables.bootstrap4.min.js,/public/js/plugins/fullcalendar/moment.min.js,/public/js/plugins/jsTree/jstree.min.js,/public/js/plugins/sweetalert/sweetalert2.all.min.js,/public/js/plugins/ladda/spin.min.js,/public/js/plugins/ladda/ladda.min.js,/public/js/plugins/ladda/ladda.jquery.min.js,/public/js/plugins/select2/select2.full.min.js,/public/js/plugins/dropzone/dropzone.js,/public/js/plugins/switchery/switchery.js,/public/js/plugins/daterangepicker/daterangepicker.js,/public/js/plugins/datapicker/bootstrap-datepicker.js,/public/js/plugins/validate/jquery.validate.min.js,/public/js/plugins/validate/validate_zh.js,/modular/utils.js,/modular/receiveOrder/wmsReceiveOrder.js')"><!-- layout文件路径-->
<div th:fragment="content">
    <div class="ibox float-e-margins">
       
        <div class="ibox-content">
            <div class="table-responsive">
                <P>
                    <shiro:hasPermission name="roleAdd">  

                    </shiro:hasPermission>
                    <button id="detailBtn" class="btn btn-info " type="button"><i class="fa fa-trash-o"></i> 查看</button>
                    <button id="submitBtn" class="btn btn-info " type="button"><i class="fa fa-trash-o"></i> 提交</button>
                    <button id="importBtn" class="btn btn-info " type="button"><i class="fa fa-trash-o"></i> 导入</button>
                    <button id="printBtn" class="btn btn-info " type="button"><i class="fa fa-trash-o"></i> 打印</button>
                    <button id="dowloadBtn" class="btn btn-info " type="button"><i class="fa fa-trash-o"></i> 模板下载</button>
                    <button id="InOrderBtn" class="btn btn-info " type="button"><i class="fa fa-trash-o"></i> 生成入库单数据</button>
                    <button id="refreshBt" class="btn btn-info " type="button"><i class="fa fa-refresh"></i> 刷新</button>
                </P>
                <p>

                </p>
                <table id="wmsReceiveOrder_table_id" class="table table-striped table-bordered hover" style="width:100%">
                    <thead>
                    <tr>
                        <th>序号</th>
                        <th>收货单号</th>
                        <th>收货日期</th>
                        <th>收货人</th>
                        <th>供应商编号</th>
                        <th>供应商名称</th>
                        <th>总托数</th>
                        <th>总件数</th>
                        <th>送货单号</th>
                        <th>创建人</th>
                        <th>创建日期</th>
                        <th>状态</th>
                    </tr>
                    </thead>
                    <tbody>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
   
   
</div>

</html>

通过上面的引入js文件将js文件引入

其中wmsReceiveOrder.js是自己编写的js文件。

初始化DataTables

在wmsReceiveOrder.js中 

/ DataTable初始化
  var t = dataTableInit();
  //---------------------------点击事件区域-------------------------
  //DataTable 行点击事件,用来设置样式点击事件
  $('#wmsReceiveOrder_table_id tbody').on('click', 'tr', function () {
    if (!$(this).hasClass('selected') ) {
      t.$('tr.selected').removeClass('selected');
      $(this).addClass('selected');
    }
  } );
  //DataTable重新渲染时序号一栏重新进行编号点击事件
  t.on( 'draw.dt', function () {
    var PageInfo = $('#wmsReceiveOrder_table_id').DataTable().page.info();
    t.column(0, { page: 'current' }).nodes().each( function (cell, i) {
      cell.innerHTML = i + 1 + PageInfo.start;
    } );
  } );
  //刷新按钮事件
  $("#refreshBt").click(function () {
    // 刷新表格数据,分页信息不会重置
    t.ajax.reload( null, false );
  });
 


    //模板下载按钮点击事件
    $("#dowloadBtn").click(function () {
        templateDowload()
    });
  //导入按钮点击事件
    $("#importBtn").click(function () {
        importExcel();
    });
    //打印按钮点击事件
    $("#printBtn").click(function () {
        var data = t.rows(['.selected']).data()[0];
        debugger
        if(undefined===data){
            debugger
            swal({
                type: 'warning',
                title: '提示:',
                text: '请首先选择一行数据!',
                confirmButtonColor: "#1ab394",
            })
        }else if(data.status.trim()==="1") {
            debugger
            swal({
                type: 'warning',
                title: '提示:',
                text: '请先提交!',
                confirmButtonColor: "#1ab394",
            })
        }else
            printCode(data.id);

    });

    //生成入库单数据按钮点击事件
    $("#InOrderBtn").click(function () {
        var data = t.rows(['.selected']).data()[0];
        debugger
        if(undefined===data){
            swal({
                type: 'warning',
                title: '提示:',
                text: '请首先选择一行数据!',
                confirmButtonColor: "#1ab394",
            })
        }else if((data.status.trim()==="4")) {
            swal({
                type: 'warning',
                title: '提示:',
                text: '已经生成了入库单数据!',
                confirmButtonColor: "#1ab394",
            })
       }elseif(data.status.trim()==="1"||data.status.trim()==="2") {
            debugger
            swal({
                type: 'warning',
                title: '提示:',
                text: '打印后才能生成入库单数据!',
                confirmButtonColor: "#1ab394",
            })
        }else
            submitInOrder(data.id);

    });
   
    //提交按钮点击事件
    $("#submitBtn").click(function () {
        var data = t.rows(['.selected']).data()[0];
        if(undefined===data){
            swal({
                type: 'warning',
                title: '提示:',
                text: '请首先选择一行数据!',
                confirmButtonColor: "#1ab394",
            })
        } else if(data.status.trim()==="3") {
            debugger
            swal({
                type: 'warning',
                title: '提示:',
                text: '已打印不能再提交!',
                confirmButtonColor: "#1ab394",
            })
        }else if(data.status.trim()==="4") {
            debugger
            swal({
                type: 'warning',
                title: '提示:',
                text: '已入库不能再提交!',
                confirmButtonColor: "#1ab394",
            })
        }
        else if(data.status.trim()==="2") {
            debugger
            swal({
                type: 'warning',
                title: '提示:',
                text: '该订单状态已提交!',
                confirmButtonColor: "#1ab394",
            })
        }else{
            submitPrint(data.id);
        }

    });



  function dataTableInit(){
    return $('#wmsReceiveOrder_table_id').DataTable({
      "language": {
        "processing": "处理中...",
        "lengthMenu": "显示 _MENU_ 项结果",
        "zeroRecords": "没有匹配结果",
        "info": "显示第 _START_ 至 _END_ 项结果,共 _TOTAL_ 项",
        "infoEmpty": "显示第 0 至 0 项结果,共 0 项",
        "infoFiltered": "(由 _MAX_ 项结果过滤)",
        "infoPostFix": "",
        "search": "搜索:",
        "searchPlaceholder": "搜索...",
        "url": "",
        "emptyTable": "表中数据为空",
        "loadingRecords": "载入中...",
        "infoThousands": ",",
        "paginate": {
          "first": "首页",
          "previous": "上页",
          "next": "下页",
          "last": "末页"
        },
        "aria": {
          paginate: {
            first: '首页',
            previous: '上页',
            next: '下页',
            last: '末页'
          },
          "sortAscending": ": 以升序排列此列",
          "sortDescending": ": 以降序排列此列"
        },
        "decimal": "-",
        "thousands": "."
      },
      "processing": true,
      "searching" : false,
      "serverSide": true,
        "stateSave": true,
        "pageLength": 5,
        "lengthMenu": [ 5,10, 25, 50, 75, 100 ],
      "dom": '<"top">rt<"bottom"flpi><"clear">',
      "columnDefs": [ {
        "searchable": false,
        "orderable": false,
        "targets": 0
      }],
      columns: [
        { data: 'id' },
        { data: 'purchaseCode' },
          { data: 'deliveryTime',
              render: function (data, type, full, meta ) {
                  return moment(data).format("YYYY-MM-DD ");
              } },
          { data: 'createrName' },
          { data: 'supplierCode' },
          { data: 'supplierName' },
          { data: 'totalTray' },
          { data: 'totalNum' },
          { data: 'deliveryCode' },
          { data: 'createrName' },
          { data: 'gmtCreat',
              render: function (data, type, full, meta ) {
                  return moment(data).format("YYYY-MM-DD HH:mm:ss");
              } },

          { data: 'status',
              render: function (data, type, full, meta ) {
                  if(data.trim()=="1"){
                      return '未提交'
                  }else if(data.trim()=="2"){
                      return '已提交'
                  }else if(data.trim()=="3"){
                      return '已打印'
                  }else if(data.trim()=="4"){
                     return '已入库'
                  }else{
                      return '未知状态'
                  }
              }  },
      ],
      "ajax": function (data, callback, setting) {
          $.each(data.columns,function (index,value) {
              //匹配所有input
              $("#searchCondition").find('input[type="text"]').each(function () {
                  if(value.data === $(this).attr('id')){
                      value.search.value = $(this).val();
                  }
              });
              //匹配所有select
              debugger
              $("#searchCondition select").each(function () {
                  debugger
                  if(value.data === $(this).attr('id')){
                      value.search.value = $(this).val();
                  }
              });
          })
        $.ajax({
          type: 'POST',
          url: "/wmsReceiveOrder/doPageForReceiveOrderTable",
          cache: false,  //禁用缓存
          data: JSON.stringify(data),  //传入组装的参数
          contentType: "application/json",
          dataType: "json",
          success: function (result) {
            debugger
            callback(result);
          }
        })
      }
    })
  }

 

在js中先进行dataTables初始化,然后国际化配置,然后进行数据填充,最后进行ajax请求数据。

后台返回数据

在后台Controller中

@Description("获取数据接口")
    @ResponseBody
    @RequestMapping(value = "/doPageForReceiveOrderTable")
    public DataTablesResultJsonVO doPageForMaterielTable(@RequestBody DataTablesJsonVO vo) {
        DataTablesResultJsonVO dataTablesResultJsonVO = new DataTablesResultJsonVO();
        try {
            String keyHump = vo.getColumns().get(vo.getOrder().get(0).getColumn().intValue()).getData();
            String keyLine = StringUtil.humpToLine(keyHump);
            String sortStr = vo.getOrder().get(0).getDir();
            Page<WmsReceiveOrderVO> pageEntity = new Page<>(vo.getStart()/vo.getLength()+1, vo.getLength());
            IPage<WmsReceiveOrderVO> page = receiveOrderService.pageTray(pageEntity, vo);
            dataTablesResultJsonVO.setData(page.getRecords());
            dataTablesResultJsonVO.setDraw(vo.getDraw());
            dataTablesResultJsonVO.setError("error");
            dataTablesResultJsonVO.setRecordsFiltered(page.getTotal());
            dataTablesResultJsonVO.setRecordsTotal(page.getSize());
            Log.getInst(this).debug("doPageForRoleTable test:" + vo.getColumns().get(0).getSearch());
            return dataTablesResultJsonVO;
        } catch (Exception ex) {
            Log.getInst().debug("获取数据接口:",ex);
            dataTablesResultJsonVO.setData(new ArrayList<WmsReceiveOrderVO>());
            dataTablesResultJsonVO.setDraw(vo.getDraw());
            dataTablesResultJsonVO.setError("error");
            dataTablesResultJsonVO.setRecordsFiltered(0L);
            dataTablesResultJsonVO.setRecordsTotal(0L);
            Log.getInst(this).debug("doPageForRoleTable test:" + vo.getColumns().get(0).getSearch());
            return dataTablesResultJsonVO;
        }

    }

使用封装的DataTablesJsonVO请求对象

import lombok.Data;

import java.io.Serializable;
import java.util.List;
@Data
public class DataTablesJsonVO implements Serializable{
    private Long draw;
    private List<DataTablesColumnsJsonVO> columns;
    private List<DataTablesOrderJsobVO> order;
    private Long start;
    private Long length;
    private DataTablesOrderJsobVO search;
}


其中DataTablesColumnsJsonVO

import lombok.Data;

import java.io.Serializable;

@Data
public class DataTablesColumnsJsonVO implements Serializable {
    private String data;
    private String name;
    private boolean searchable;
    private boolean orderable;
    private DataTablesSearchJsnVO search;
}

DataTablesOrderJsobVO

import lombok.Data;

import java.io.Serializable;

@Data
public class DataTablesOrderJsobVO implements Serializable {
    private Long column;
    private String dir;
}

使用了封装的响应DataTablesResultJsonVO

import lombok.Data;

import java.io.Serializable;
import java.util.List;

@Data
public class DataTablesResultJsonVO<T> implements Serializable {
    private Long draw;
    private Long recordsTotal;
    private Long recordsFiltered;
    private List<T> data;
    private String error;
}

要显示的数据通过receiveOrderService.pageTray(pageEntity, vo);
查询获取。

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

霸道流氓气质

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值