參考自官方文檔,需要引入jquery.js,jquery.dataTables.js,dataTables.bootstrap.js(可選),
由於時間緊,省略了很多,所以總結份簡化版的僅供參考。
1、直接加載,這個比較簡單,如下
<div id="tid" class="col-sm-12 col-md-12"> <div id="secondtid" hidden="hidden"></div> </div>
jsp用了bootstrap的柵格,js如下
<script type="text/javascript"> function getgaoxinqu() { $('#secondtid').remove(); $("#tid").append( "<div id='secondtid' style='width: 100%;'><table id='table_id' class='table table-striped table-bordered table-hover no-footer dataTable display' ><thead><tr><th nowrap>id</th><th nowrap>高新區名稱</th><th nowrap>地區</th><th nowrap>工商注冊企業數</th><th nowrap>網址</th><th nowrap>工業總產值(千元)</th><th nowrap>工業增加值(千元)</th><th nowrap>主導產業</th><th nowrap>財政收入(萬元)</th><th nowrap>財政支出(萬元)</th></tr></thead><tbody></tbody></table></div>"); $.ajax({ url : '${contextPath}/mst/theme/otherOperatePlatformTheme.do?flag=gaoxinqu',// 跳轉到 action data : { barName : '1' }, serverSide: true,//服務器處理 traditional : true, type : 'post', success : function(data) { var dataObj = eval(data); $('#table_id').DataTable( { data : dataObj, sScrollY: 600, sScrollX: '100%', columns : [ { data : 'id' },{ data : 'name' }, { data : 'dy' }, { data : 'gxqyy' }, { data : 'www' }, { data : 'gysum' }, { data : 'gyadd' }, { data : 'zdcy' } , { data : 'cztr' } , { data : 'czzc' } ], order:[[ 0, "asc" ]], language : { search : "在表格中搜索:", show : "顯示", "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" : ": 以降序排列此列" } } }); showPage(); }, error : function() { alert("異常!"); } }); showPage();//高度調節 } </script>
後台傳個json就行了,由於這個破項目表名都很奇葩湊合看吧。
List<GaoXinDistrict> gxlist=new ArrayList<GaoXinDistrict>(); String sql="select * from ODS10000060"; try { List<Map> list = oracledictionaryService.executeSqlToRecordMap(sql); for (Map map : list) { GaoXinDistrict gx=new GaoXinDistrict(); Object id= map.get("ID"); Object name = map.get("NAME"); Object JB = map.get("JB"); Object DY = map.get("DY"); Object YEAR = map.get("YEAR"); Object FZR = map.get("FZR"); Object TBR = map.get("TBR"); Object phone = map.get("PHONE"); Object EMAIL = map.get("EMAIL"); Object WWW = map.get("WWW"); Object GXQMJSUM = map.get("GXQMJSUM"); Object JCMJ = map.get("JCMJ"); Object GXQYY = map.get("GXQYY"); Object GYSUM = map.get("GYSUM"); Object GYADD = map.get("GYADD"); Object CZTR = map.get("CZTR"); Object CZZC = map.get("CZZC"); Object DEC = map.get("DEC"); Object ZDCY = map.get("ZDCY"); gx.setId(Integer.parseInt(String.valueOf(id))); gx.setName(name.toString()); gx.setJB(JB.toString()); gx.setDY(DY.toString()); gx.setYEAR(YEAR.toString()); gx.setFZR(FZR.toString()); gx.setTBR(TBR.toString()); gx.setPhone(phone.toString()); gx.setEMAIL(EMAIL.toString()); gx.setWWW(WWW.toString()); gx.setGXQMJSUM(GXQMJSUM.toString()); gx.setJCMJ(JCMJ.toString()); gx.setGXQYY(GXQYY.toString()); gx.setGYSUM(GYSUM.toString()); gx.setGYADD(GYADD.toString()); gx.setCZTR(CZTR.toString()); gx.setCZZC(CZZC.toString()); gx.setDEC(DEC.toString()); gx.setZDCY(ZDCY.toString()); gxlist.add(gx); } parseJSONResult(gxlist, response); } catch (Exception e) { e.printStackTrace(); }
2、延遲加載
由於老項目用的struts1,造成前台form接收參數有問題,所以直接用servlet接收
前端jsp如1直接加載一樣,js如下
function initDatatables(){ /*var columns = new Array(); $("#listTable thead th").each(function(index, element) { var fieldName=$(element).attr("fieldName"); if(fieldName.indexOf('.')>0)fieldName=fieldName.substring(2); columns.push({"data":fieldName}); }); if($('#listTable').length<=0) return; //-- 列定義 var columnDefs = new Array(); $("#listTable thead th").each(function(index, element) { if($(element).attr("fieldType")!='VARCHAR'){ columnDefs.push({ "orderable": true, "searchable" : false, "targets": index }); } });*/ $('#listTable').DataTable( { "processing": true,//處理中顯示 "serverSide": true,//服務器處理 "sScrollY": 300, "sScrollX": "100%", "columns":[{"data":"ID"},{"data":"YEAR"},{"data":"REGION"},{"data":"GYZCZ"},{"data":"QYS"}], /*"columns":columns,*/ /*"columnDefs":columnDefs,*/ // "bInfo": false, // "bPaginate": false, // "bFilter":false,/servlet/ComplexInquireServlet // "bLengthChange": false, "ajax": { "url": urlContextPath+"/mst/DatatablesLazyLoadServlet?flag=details", "type": "POST", "data": function ( d ) { var queryForm = document.queryConditionForm; d['fieldCode'] = 'ID,YEAR,REGION,GYZCZ,QYS'; d['tableCode'] = 'ODS10000030'; //表名 } }, "oLanguage": { "search" : "在表格中搜索:", "show" : "顯示", "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" : ": 以降序排列此列" } } } ); showPage(); } function showQueryTable(){ //建table $('#secondtid').remove(); $("#tid").append( "<div id='secondtid' style='width: 100%;'>" + "<table id='listTable' class='table table-striped table-bordered table-hover no-footer dataTable display' ><thead><tr>" + "<th nowrap>id</th>" + "<th nowrap>年份</th>" + "<th nowrap>地區</th>" + "<th nowrap>工業總產值(萬元)</th>" + "<th nowrap>企業數(家)</th>" + "</tr></thead><tbody></tbody></table>" + "</div>"); //創建表頭 /*$.ajax({ url : urlContextPath+'/mst/DatatablesLazyLoadServlet?flag=titles',// 跳轉到 action data : { index : '' }, type : 'post', success : function(data) { var dataObj = eval(data); }, error : function() { alert("異常!"); } });*/ //填充數據 initDatatables(); }
注:這個已經是簡化版的了,表頭可以用另一個ajax傳過來,這裡省略直接寫死了。
下面是後台部分
public class DatatablesLazyLoad extends HttpServlet{ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.process(request, response); } /** * datatables 延遲加載 數據加載,flag標注details表示注入數據,titles表示注入標題。 * @param request * @param response */ private void process(HttpServletRequest request, HttpServletResponse response) { ServletContext servletContext=request.getSession().getServletContext(); WebApplicationContext wac =WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext); DictionaryServiceImpl ds=(DictionaryServiceImpl)wac.getBean("oracledictionaryService"); String flag = request.getParameter("flag"); String tableCode = request.getParameter("tableCode"); String fieldCode = request.getParameter("fieldCode"); if(flag==null)return; if(flag.equals("titles")){ }else if(flag.equals("details")){ String draw = request.getParameter("draw"); String start = request.getParameter("start"); String length = request.getParameter("length"); StringBuilder sql = new StringBuilder("select "); List titles = this.getTitles(tableCode,fieldCode,ds); for(int i=0;i<titles.size();i++){ Map record = (Map)titles.get(i); sql.append(" ").append(record.get("FIELDNAME")).append(", "); } if(sql.lastIndexOf(",")>0) sql.deleteCharAt(sql.lastIndexOf(",")); sql.append(" from ").append(tableCode); sql.append(" where 1=1 "); String filterSql = getFilterSql(titles,request); Integer totalCount =ds.getSqlRecordCount("select count(*) from (" + sql.toString()+ ") tmp"); Integer filterCount = ds.getSqlRecordCount("select count(*) from (" + sql.toString()+filterSql+ ") tmp"); String[] strings = fieldCode.split(","); String orderSql = getOrderSql(strings,request); sql.append(filterSql); sql.append(orderSql); List<Map> lt = ds.executeSqlToRecordMap(sql.toString(),Integer.valueOf(start),Integer.valueOf(length)); Map result = new LinkedHashMap(); result.put("draw", draw); result.put("recordsTotal", totalCount);//記錄總行數 result.put("recordsFiltered", filterCount);//過濾的行數 int count=Integer.valueOf(length)+1; for(Map r : lt){ r.put("DT_RowId", r.get("id"));//設置行主鍵 Map rowDate = new LinkedHashMap();//row data rowDate.putAll(r); r.put("DT_RowData", rowDate); r.put("countInx", count); count++; } result.put("data", lt); try { convertListToJson(result, response); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } /** * 得到所有的列標題名稱 * @return */ private List getTitles(String tableCode,String fieldCode,DictionaryServiceImpl ds){ /*StringBuilder sql = new StringBuilder("select UPPER(ODS_DF_NAME) fieldName,ODS_DF_CN_NAME fieldLabel,ODS_DF_CODE fieldCode,UPPER(ODS_DF_DATA_TYPE) fieldType from ODS.ODS_DF_INFO_REG "); sql.append(" where ODS_TB_CODE= '"+tableCode+"' "); List<Map> list = ds.executeSqlToRecordMap(sql.toString()); return list;*/ StringBuilder sql = new StringBuilder("select UPPER(ODS_DF_NAME) fieldName,ODS_DF_CN_NAME fieldLabel,ODS_DF_CODE fieldCode,UPPER(ODS_DF_DATA_TYPE) fieldType from ODS.ODS_DF_INFO_REG "); sql.append(" where 1=1 "); sql.append(" and ODS_TB_CODE = '"+tableCode+"'"); sql.append(" and ODS_DF_NAME in ("); String[] tmp = fieldCode.split(","); StringBuilder ids = new StringBuilder(); for(String t : tmp){ if(StringUtils.isEmpty(t)) continue; ids.append("'").append(t).append("',"); } if(ids.lastIndexOf(",")>0) ids.deleteCharAt(ids.lastIndexOf(",")); sql.append(ids); sql.append(")"); List lt = ds.executeSqlToRecordMap(sql.toString()); return lt; } /** * 前台搜索 * @param fieldLt * @return */ private String getFilterSql(List<Map> fieldLt,HttpServletRequest request) { StringBuilder filterSql = new StringBuilder(" and ( "); String searchKey = "search[value]"; String searchValue = request.getParameter(searchKey); System.out.println(searchValue); if(StringUtils.isEmpty(searchValue)) return ""; List<String> filterDetail = new ArrayList(); for(int i=0;i<fieldLt.size();i++){ Map field = fieldLt.get(i); if(field.get("FIELDTYPE").equals("VARCHAR")){ String subKey = "columns["+i+"][searchable]"; if("true".equals(request.getParameter(subKey))){ String fieldName = field.get("FIELDNAME").toString(); String subSql = fieldName + " like '%"+searchValue+"%'"; filterDetail.add(subSql); } } } if(filterDetail.size()==0) return ""; boolean f = true; for(String subSql : filterDetail){ if(f){ f= false; filterSql.append(subSql); }else{ filterSql.append(" OR ").append(subSql); } } filterSql.append(")"); return filterSql.toString(); } /** * 排序 * @param fieldLt * @return */ private String getOrderSql(String[] titles,HttpServletRequest request){ StringBuilder orderSql = new StringBuilder(" order by "); String indexKey = "order[0][column]"; String dirKey = "order[0][dir]"; Integer columnIndex = Integer.valueOf(request.getParameter(indexKey)); String dir = request.getParameter(dirKey); if(columnIndex<=titles.length){ orderSql.append(titles[columnIndex]).append(" ").append(dir); return orderSql.toString(); } return ""; } public void convertListToJson(Map map,HttpServletResponse response)throws Exception{ JSONArray json = JSONArray.fromObject(map); response.setHeader("Cache-Control", "no-cache"); response.setContentType("text/html; charset=GBK"); PrintWriter writer; writer = response.getWriter(); writer.write(json.get(0).toString()); writer.close(); } }
總結,做的比較急,也沒好好整理下直接貼出來,因為也不難,肯定有地方寫的不好,僅供參考。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持。