当前位置: 代码迷 >> 综合 >> datatables+java实现服务器端分页,排序,查询,列的显示影藏
  详细解决方案

datatables+java实现服务器端分页,排序,查询,列的显示影藏

热度:81   发布时间:2023-12-14 05:26:49.0

最近看了下datatables,模仿写了一个小例子,和大家分享一下。效果图如下


jsp代码:

[html] view plaincopy
print?
  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  2. <%  
  3. String path = request.getContextPath();  
  4. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  5. %>  
  6. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  7. <html>  
  8. <head>  
  9. <base href="<%=basePath%>">  
  10. <title>快递公司列表</title>  
  11. <meta http-equiv="pragma" content="no-cache">  
  12. <meta http-equiv="cache-control" content="no-cache">  
  13. <meta http-equiv="expires" content="0">  
  14. <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  15. <meta http-equiv="description" content="This is my page">  
  16. <link rel="stylesheet" type="text/css" href="css/jquery.dataTables.css">  
  17. <script type="text/javascript" charset="utf8" src="js/jquery-1.9.1.min.js"></script>  
  18. <script type="text/javascript" charset="utf8" src="js/jquery.dataTables.js"></script>  
  19. <script type="text/javascript">  
  20.     var rootPath = '${pageContext.request.contextPath}';  
  21. </script>  
  22. </head>  
  23. <body>  
  24.     <form>  
  25.         <span>编号:</span> <input type="text" placeholder="编号" id="id-search">  
  26.         <span>名称:</span> <input type="text" placeholder="名称" id="name-search">  
  27.         <span>状态:</span> <select id="status-search">  
  28.             <option value="">全部</option>  
  29.             <option value="1">可以查发</option>  
  30.             <option value="2">可以链接</option>  
  31.             <option value="3">仅供查询</option>  
  32.             <option value="4">不可用</option>  
  33.         </select>  
  34.         <button type="button" id="btn_search">查询</button>  
  35.           
  36.         <a href="#" data-column="0">影藏编号</a>  
  37.         <a href="#" data-column="1">影藏名称</a>  
  38.         <a href="#" data-column="2">影藏状态</a>  
  39.         <a href="#" data-column="3">影藏电话</a>  
  40.         <a href="#" data-column="4">影藏网址</a>  
  41.         <a href="#" data-column="5">影藏操作</a>  
  42.     </form>  
  43.     <table id="table" class="display">  
  44.         <thead>  
  45.             <tr>  
  46.                 <th>编号</th>  
  47.                 <th>名称</th>  
  48.                 <th>状态</th>  
  49.                 <th>电话</th>  
  50.                 <th>网址</th>  
  51.                 <th>操作</th>  
  52.             </tr>  
  53.         </thead>  
  54.         <tbody></tbody>  
  55.     </table>  
  56.     <script type="text/javascript" src="js/constant.js"></script>  
  57.     <script type="text/javascript">  
  58.     $(function(){  
  59.         var $table = $("#table");  
  60.         var _table = $table.dataTable($.extend(true,{},CONSTANT.DATA_TABLES.DEFAULT_OPTION, {  
  61.             ajax : function(data, callback, settings) {  
  62.                 //封装请求参数  
  63.                 var param = userManage.getQueryCondition(data);  
  64.                 $.ajax({  
  65.                         type: "GET",  
  66.                         url: rootPath+"/carrier/getCarrierByPage.action",  
  67.                         cache : false,  //禁用缓存  
  68.                         data: param,    //传入已封装的参数  
  69.                         dataType: "json",  
  70.                         success: function(result) {  
  71.                                 //异常判断与处理  
  72.                                 if (result.errorCode) {  
  73.                                     alert("查询失败");  
  74.                                     return;  
  75.                                 }  
  76.                                 //封装返回数据  
  77.                                 var returnData = {};  
  78.                                 returnData.draw = data.draw;//这里直接自行返回了draw计数器,应该由后台返回  
  79.                                 returnData.recordsTotal = result.total;//总记录数  
  80.                                 returnData.recordsFiltered = result.total;//后台不实现过滤功能,每次查询均视作全部结果  
  81.                                 returnData.data = result.pageData;  
  82.                                 //调用DataTables提供的callback方法,代表数据已封装完成并传回DataTables进行渲染  
  83.                                 //此时的数据需确保正确无误,异常判断应在执行此回调前自行处理完毕  
  84.                                 callback(returnData);  
  85.                         },  
  86.                         error: function(XMLHttpRequest, textStatus, errorThrown) {  
  87.                             alert("查询失败");  
  88.                         }  
  89.                     });  
  90.             },  
  91.             //绑定数据  
  92.             columns: [  
  93.                 {  
  94.                     data: "carrierId",//字段名  
  95.                 },  
  96.                 {  
  97.                     data: "carrierName",//字段名  
  98.                 },  
  99.                 {  
  100.                     data : "carrierStatus",//字段名  
  101.                     render : function(data,type, row, meta) {  
  102.                         return (data == 1? "可以查发":data == 2?"可以链接":data == 3?"仅供查询":"不可用");  
  103.                     }  
  104.                 },  
  105.                 {  
  106.                     data : "carrierPhone",//字段名  
  107.                 },  
  108.                 {  
  109.                     data : "carrierLink",//字段名  
  110.                     orderable : false,//禁用排序  
  111.                     render : CONSTANT.DATA_TABLES.RENDER.ELLIPSIS//alt效果  
  112.                 },  
  113.                  {  
  114.                     data: null,//字段名  
  115.                     defaultContent:"",//无默认值  
  116.                     orderable : false//禁用排序  
  117.                 }  
  118.             ],  
  119.             "createdRow": function ( row, data, index ) {  
  120.                 //不使用render,改用jquery文档操作呈现单元格  
  121.                 var $btnEdit = $('<button type="button" class="btn-edit">修改</button>');  
  122.                 var $btnDel = $('<button type="button" class="btn-del">删除</button>');  
  123.                 $('td', row).eq(5).append($btnEdit).append($btnDel);  
  124.             },  
  125.             "drawCallback": function( settings ) {  
  126.                 //渲染完毕后的回调  
  127.                 //默认选中第一行  
  128.                 //$("tbody tr",$table).eq(0).click();  
  129.             }  
  130.         })).api();//此处需调用api()方法,否则返回的是JQuery对象而不是DataTables的API对象  
  131.         //查询  
  132.         $("#btn_search").click(function(){  
  133.             _table.draw();  
  134.         });  
  135.         //行点击事件  
  136.         $("tbody",$table).on("click","tr",function(event) {  
  137.             $(this).addClass("active").siblings().removeClass("active");  
  138.             //获取该行对应的数据  
  139.             var item = _table.row($(this).closest('tr')).data();  
  140.             userManage.showItemDetail(item);  
  141.         });  
  142.         //按钮点击事件  
  143.         $table.on("click",".btn-edit",function() {  
  144.             //点击编辑按钮  
  145.             var item = _table.row($(this).closest('tr')).data();  
  146.             userManage.editItemInit(item);  
  147.         }).on("click",".btn-del",function() {  
  148.             //点击删除按钮  
  149.             var item = _table.row($(this).closest('tr')).data();  
  150.             userManage.deleteItem(item);  
  151.         });  
  152.         //影藏列  
  153.         $('a').on( 'click', function (e) {  
  154.             var cut = $(this).text()  
  155.             if(cut.indexOf("显示")>-1){  
  156.                 $(this).text("影藏"+cut.split("示")[1])  
  157.             }else{  
  158.                 $(this).text("显示"+cut.split("藏")[1])  
  159.             }  
  160.             e.preventDefault();  
  161.             var column = _table.column( $(this).attr('data-column') );  
  162.             column.visible( ! column.visible() );  
  163.         } );  
  164.           
  165.     });  
  166.     var userManage = {  
  167.             getQueryCondition : function(data) {  
  168.                 var param = {};  
  169.                 //组装排序参数  
  170.                 if (data.order&&data.order.length&&data.order[0]) {  
  171.                     switch (data.order[0].column) {  
  172.                     case 0:  
  173.                         param.orderColumn = "carrier_id";//数据库列名称  
  174.                         break;  
  175.                     case 1:  
  176.                         param.orderColumn = "carrier_name";//数据库列名称  
  177.                         break;  
  178.                     case 2:  
  179.                         param.orderColumn = "carrier_status";//数据库列名称  
  180.                         break;  
  181.                     case 3:  
  182.                         param.orderColumn = "carrier_phone";//数据库列名称  
  183.                         break;  
  184.                     default:  
  185.                         param.orderColumn = "carrier_id";//数据库列名称  
  186.                         break;  
  187.                     }  
  188.                     //排序方式asc或者desc  
  189.                     param.orderDir = data.order[0].dir;  
  190.                 }  
  191.                 param.id = $("#id-search").val();//查询条件  
  192.                 param.name = $("#name-search").val();//查询条件  
  193.                 param.status = $("#status-search").val();//查询条件  
  194.                 //组装分页参数  
  195.                 param.startIndex = data.start;  
  196.                 param.pageSize = data.length;  
  197.                 param.draw = data.draw;  
  198.                 return param;  
  199.             },  
  200.             editItemInit : function(item) {  
  201.                 //编辑方法  
  202.                 alert("编辑"+item.carrierId+"  "+item.carrierName);  
  203.             },  
  204.             deleteItem : function(item) {  
  205.                 //删除  
  206.                 alert("删除"+item.carrierId+"  "+item.carrierName);     
  207.             },  
  208.             showItemDetail: function(item){  
  209.                 //点击行  
  210.                 alert("点击"+item.carrierId+"  "+item.carrierName);  
  211.             }  
  212.         };  
  213.    </script>  
  214. </body>  
  215. </html>  
[html] view plaincopy
print?
  1.   
[html] view plaincopy
print?
  1. 其余js和css都是datatables官方提供de  
[html] view plaincopy
print?
  1. constant.js代码  
[javascript] view plaincopy
print?
  1. /*常量*/  
  2. var CONSTANT = {  
  3.         DATA_TABLES : {  
  4.             DEFAULT_OPTION : { //DataTables初始化选项  
  5.                 language: {  
  6.                     "sProcessing":   "处理中...",  
  7.                     "sLengthMenu":   "每页 _MENU_ 项",  
  8.                     "sZeroRecords":  "没有匹配结果",  
  9.                     "sInfo":         "当前显示第 _START_ 至 _END_ 项,共 _TOTAL_ 项。",  
  10.                     "sInfoEmpty":    "当前显示第 0 至 0 项,共 0 项",  
  11.                     "sInfoFiltered""(由 _MAX_ 项结果过滤)",  
  12.                     "sInfoPostFix":  "",  
  13.                     "sSearch":       "搜索:",  
  14.                     "sUrl":          "",  
  15.                     "sEmptyTable":     "表中数据为空",  
  16.                     "sLoadingRecords""载入中...",  
  17.                     "sInfoThousands":  ",",  
  18.                     "oPaginate": {  
  19.                         "sFirst":    "首页",  
  20.                         "sPrevious""上页",  
  21.                         "sNext":     "下页",  
  22.                         "sLast":     "末页",  
  23.                         "sJump":     "跳转"  
  24.                     },  
  25.                     "oAria": {  
  26.                         "sSortAscending":  ": 以升序排列此列",  
  27.                         "sSortDescending"": 以降序排列此列"  
  28.                     }  
  29.                 },  
  30.                 autoWidth: false,   //禁用自动调整列宽  
  31.                 stripeClasses: ["odd""even"],//为奇偶行加上样式,兼容不支持CSS伪类的场合  
  32.                 order: [],          //取消默认排序查询,否则复选框一列会出现小箭头  
  33.                 processing: false,  //隐藏加载提示,自行处理  
  34.                 serverSide: true,   //启用服务器端分页  
  35.                 searching: false    //禁用原生搜索  
  36.             },  
  37.             COLUMN: {  
  38.                 CHECKBOX: { //复选框单元格  
  39.                     className: "td-checkbox",  
  40.                     orderable: false,  
  41.                     width: "30px",  
  42.                     data: null,  
  43.                     render: function (data, type, row, meta) {  
  44.                         return '<input type="checkbox" class="iCheck">';  
  45.                     }  
  46.                 }  
  47.             },  
  48.             RENDER: {   //常用render可以抽取出来,如日期时间、头像等  
  49.                 ELLIPSIS: function (data, type, row, meta) {  
  50.                     data = data||"";  
  51.                     return '<span title="' + data + '">' + data + '</span>';  
  52.                 }  
  53.             }  
  54.         }  
  55. };  
后台代码:

[java] view plaincopy
print?
  1. @RequestMapping(value = "/getCarrierByPage")  
  2.     @ResponseBody  
  3.     public String getCarrierByPage() throws Exception{  
  4.         //直接返回前台  
  5.         String draw = request.getParameter("draw");  
  6.         //数据起始位置  
  7.         String startIndex = request.getParameter("startIndex");  
  8.         //每页显示的条数  
  9.         String pageSize = request.getParameter("pageSize");  
  10.         //获取排序字段  
  11.         String orderColumn = request.getParameter("orderColumn");  
  12.         if(orderColumn == null){  
  13.             orderColumn = "carrier_id";  
  14.         }  
  15.         //获取排序方式  
  16.         String orderDir = request.getParameter("orderDir");  
  17.         if(orderDir == null){  
  18.             orderDir = "asc";  
  19.         }  
  20.         //查询条件  
  21.         String carrierId = request.getParameter("id");  
  22.         String carrierName = request.getParameter("name");  
  23.         String carrierStatus = request.getParameter("status");  
  24.         XcxCarrier x = new XcxCarrier();  
  25.         if(null != carrierId && !"".equals(carrierId)){  
  26.             x.setCarrierId(Long.parseLong(carrierId));  
  27.         }  
  28.         x.setCarrierName(carrierName);  
  29.         if(null != carrierStatus && !"".equals(carrierStatus)){  
  30.             x.setCarrierStatus(Integer.parseInt(carrierStatus));  
  31.         }  
  32.         PageHelper.offsetPage(getPageNo(Integer.parseInt(startIndex)), getPageSize(Integer.parseInt(pageSize)));  
  33.         List<XcxCarrier> result = this.xcxCarrierService.querySelectByCondition(orderColumn, orderDir, x);  
  34.         PageInfo<XcxCarrier> pageInfo = new PageInfo<XcxCarrier>(result);  
  35.         Map<Object, Object> info = new HashMap<Object, Object>();  
  36.         System.out.println(JSONObject.fromObject(pageInfo));  
  37.         info.put("pageData", pageInfo.getList());  
  38.         info.put("total", pageInfo.getTotal());  
  39.         info.put("draw", draw);  
  40.         return JSONObject.fromObject(info)+"";  
  41.     }  

到此,一个简单的demo就完成了,如果有疑问,可以访问datatables的官网查看api文档。再次感谢DataTables中文网交流群 547691991中提供的demo。
  相关解决方案