jQuery datatables使用 ( 封装类实现前台分页 二 续...)

来源:互联网 发布:阿里云注册域名 编辑:程序博客网 时间:2024/05/22 05:30
 

封装的公用分页的工具类:

package com.sintai.util;

 

import java.util.ArrayList;

import java.util.List;

 

public class PageUtil<T> {

    // 分页静态不变属性

    public static final String SIZE = "size";   //每页显示的记录数

    public static final String CURPAGE = "curPage";   //总页数

 

    private long total;

    private List<T> data = new ArrayList<T>();

   

//省略set get 方法

 

    @Override

    public String toString() {

       return "PageUtil [data=" + data + ", total=" + total + "]";

    }

}

 

 

后台Action:

/**

     * 分页时每页跨度数量

     */

    private String parm_iDisplayStart;

    /**

     * DataTable请求服务器端次数

     */

    private String parm_sEcho;

    /**

     * 数组的数组,表格中的实际数据.

     */

    private String[][] aaData;

    /**

     * 给前台的数据

     */

    private DataTableReturnObject tableReturnObject =null;

    /**

     * 传参

     */

    private String parm_name;

 

// 省略了get set 方法

 

@Action("/findAllSite")

    public  String findAllSite(){

       List<SiteManagement> siteListPage=null;

       int totle = 0;

       try {

           Map<String, Object> params = new HashMap<String, Object>();

           int ri = Integer.parseInt(parm_iDisplayStart);

           int cup = (int) (ri / 10) + 1;

           params.put(PageUtil.CURPAGE, cup);

           params.put(PageUtil.SIZE, 10);

           PageUtil<SiteManagement> pageUtil = siteManagementManager.queryByPager(params, parm_name);

           siteListPage = pageUtil.getData();

           totle = (int) pageUtil.getTotal();

       } catch (Exception e) {

           e.printStackTrace();

           return "updateUserERROR";

       }

 

 // resultArr数组封装了页面要显示的数据以及页面显示数据的各种格式

       String[][] resultArr = new String[siteListPage.size()][];

 

       for (int i = 0; i < resultArr.length; i++) {

           String[] resultOne = new String[4];   //封装前台页面需要现实的数据

           SiteManagement site = siteListPage.get(i);

           int oID = site.getSiteManagementID();

           resultOne[0] = "<input type='checkbox' name='organizationId' value='" + oID + "' onclick='sOrgaId("+i+")' />";

           resultOne[1] = site.getSiteName();

            resultOne[2] =site.getSiteTel() ;

           resultOne[3] =site.getSiteFax();

           resultArr[i] = resultOne;

       }

       aaData = resultArr;

       tableReturnObject = new DataTableReturnObject(totle, totle, parm_sEcho, aaData); 

       return "ajax";

}

 

前台分页显示页面:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<%@ taglib prefix="s" uri="/struts-tags" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

  <head>

 

    <title>机构设置</title>

   

    <meta http-equiv="pragma" content="no-cache">

    <meta http-equiv="cache-control" content="no-cache">

    <meta http-equiv="expires" content="0">   

    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">

    <meta http-equiv="description" content="This is my page">

    <%@ include file="../taglibs.jsp" %>

    <script type="text/javascript" src="${ctx}/js/common/selectFun.js"></script>

   

<!—需要引入的固定样式和js文件-->

<link rel="stylesheet" type="text/css"href="${ctx}/css/common/dialog.css">

    <link href="${ctx}/css/common/style1.css" style="text/css" rel="stylesheet">

    <link rel="stylesheet" href="${ctx}/css/dataTables/demo_page.css" type="text/css" />

    <link rel="stylesheet" href="${ctx}/css/dataTables/demo_table.css" type="text/css" />

    <script type="text/javascript" language="javascript" src="${ctx}/js/dataTables/jquery.dataTables.js"></script>

 

</head> 

<body>

<!-- 显示区域 -->

<fieldset>

    <legend>机构管理</legend>

    <form class="feildset clearfix dataForm ">

       <table class="gridtable" style="width:100%" id="organizationTable">

           <thead>

               <tr>

                  <th width="10%" align="center">

<input type="checkbox" />

</th>

                  <th width="30%" align="center">机构名称</th>

                  <th width="30%" align="center">电话号码</th>

                  <th width="30%" align="center"> 传真 </th>

              </tr>

           </thead>

       <tbody align="center">

             <!—自动接收后台数据,按规定格式显示-->

       </tbody>  

          

       </table>

    </form>

</fieldset>

</body>

<script type="text/javascript">

       var sAjaxSource="findAllSite.action";

       var aoColumns=[ //设定各列宽度

        {"sWidth": "10%"},

        {"sWidth": "30%"},

        {"sWidth": "30%"},

        {"sWidth": "30%"}

        ];

       var iDisplayLength=10;

    var tableId="#organizationTable";

 

    var oTable;

    /**

     * 后台分页

     */

    function retrieveData( sSource, aoData, fnCallback ) {

           aoData.push({"name":"name","value":$("input[name='siteName']").val()});

    for(var i=0;i<aoData.length;i++) {

    //alert(aoData[i].name);

          aoData[i].name="parm_"+aoData[i].name.toString();

    }

 

       $.ajax({

       type: "post",

       dataType:'json', //接受数据格式

       cache:false,

       data:aoData,

       url: sSource,

       beforeSend: function(XMLHttpRequest){

       //ShowLoading();

       },

       success: function(data, textStatus){

           if(data.tableReturnObject.aaData==""){

           alert("无相关数据,请刷新");

              }

           fnCallback(data.tableReturnObject);

       },

       complete: function(XMLHttpRequest, textStatus){

       //HideLoading();

       },

       error: function(){

       //请求出错处理

           alert("error");

       }

       });

      

       }

 

    //“检索”按钮的处理函数

     function search() {

     if (oTable == null) { //仅第一次检索时初始化Datatable

     oTable = $(tableId).dataTable( {

     "bAutoWidth": false, //不自动计算列宽度

     "aoColumns": aoColumns,

     "bSort": false,

     "bProcessing": true, //加载数据时显示正在加载信息

     "bServerSide": true, //指定从服务器端获取数据

     "bFilter": false, //不使用过滤功能

     "bLengthChange": false, //用户不可改变每页显示数量

     "iDisplayLength": iDisplayLength, //每页显示10条数据

     "sAjaxSource": sAjaxSource,

     "fnServerData": retrieveData, //获取数据的处理函数

     "sPaginationType": "full_numbers", //翻页界面类型

     "headerClickable":false,

     "sortable":false

     });

     }

     }

     search();

     function btnSelect(){

        $(".paginate_active").click();   

     }

    </script>

</html>

 完善:

  DataTableReturnObject 对象具体封装的是需要返回的数据,封装的具体属性如下

public class DataTableReturnObject {

 private long iTotalRecords;
 private long iTotalDisplayRecords;
 private String sEcho;
 private String[][] aaData;

 public DataTableReturnObject(long totalRecords, long totalDisplayRecords,
   String echo, String[][] d) {
  this.iTotalRecords = totalRecords;
  this.iTotalDisplayRecords = totalDisplayRecords;
  this.sEcho = echo;
  this.aaData = d;
 }

 public long getiTotalRecords() {
  return iTotalRecords;
 }

 public void setiTotalRecords(long iTotalRecords) {
  this.iTotalRecords = iTotalRecords;
 }

 public long getiTotalDisplayRecords() {
  return iTotalDisplayRecords;
 }

 public void setiTotalDisplayRecords(long iTotalDisplayRecords) {
  this.iTotalDisplayRecords = iTotalDisplayRecords;
 }

 public String getsEcho() {
  return sEcho;
 }

 public void setsEcho(String sEcho) {
  this.sEcho = sEcho;
 }

 public String[][] getAaData() {
  return aaData;
 }

 public void setAaData(String[][] aaData) {
  this.aaData = aaData;
 }

}

 

Jquery的dataTables分页:

实现的是页面分页,在后台查询每页现实的记录,直接在页面上显示当前页的信息,所以把分页方法封装成了PageUtil类,重复使用;页面要显示的数据以及页面显示数据的输出格式甚至是添加的onclick事件等都是在后台设置完成的,页面上只需要写空的<tbody>标签体自动载入后台传过来的将要显示的数据;

注:Jquery的dataTables分页有自动的分页标签和页面样式,只需要引入就ok需要注意的是table标签的id值还有<thead>和<tbody>标签,此案例是按页数查,显示到前台页面上的值是在后台action里查出来本页之后的list,action里查出来的是当前页要显示的那部分数据