JFinal整合datatables实现的表格

本人在最近一个小项目中整合的,看到osc上还没有,就发一个先。

欢迎大侠们拍砖。

界面table的代码:
<table cellpadding="0" cellspacing="0" border="0"  class="table table-striped table-bordered" id="otable" width="100%">
    <thead>
        <tr>
            <th>ServerID</th>
             <th>SystemID</th>
             <th>服务名称</th>
             <th>Ip</th>
             <th>在线时间</th>
             <th>最后一次在线时间</th>
             <th>是否在线</th>
         </tr>
     </thead>
     <tbody>

     </tbody>
</table>


js里初始化table

oTable = $('#otable').initDT({
        "sAjaxSource": "${_BASE_PATH}/server/query"
    });


java端jfinal controller里的方法: 
public void query() {

        StringBuilder where = new StringBuilder("from dbo.GpsServerInfo where 1=1 ");
        List<String> params = new ArrayList<String>();
        if (!StringUtils.isBlank(getPara("serverID"))) {

            where.append("and ServerId like ? ");
            params.add("" + getPara("serverID") + "%");
        }
        if (!StringUtils.isBlank(getPara("serverType"))) {
            where.append("and System_ID = ?");
            params.add(getPara("serverType"));
        }

        DataTablesModel dtm = GpsServerInfo.dao.paginateDataTables(getParaToInt("page")
                .intValue(), getParaToInt("rp").intValue(),
                "select ServerID,ServerID as showID,System_ID,IpAddress,OnlineTime,LastOnlineTime,OnLineFlag ", where.toString(),params.toArray());

        List<List<String>> rows = dtm.getRows();
        for (int i = 0; i < rows.size(); i++) {
            List<String> row = rows.get(i);
            if ("1".equals(row.get(5))) {
                row.set(5, "<span class=\"label label-success\">online</span>");
            } else if ("0".equals(row.get(5))) {
                row.set(5, "<span class=\"label label-warning\">offline</span>");
            } else {
                row.set(5, "");
            }

            row.add(2, CodeConfig.getValueByKeyFromCode("configCode", row.get(1)));
        }

        this.renderJson(dtm);
    }


我针对datatables单独封装了一个分页查询,返回的结果格式的json字符串是:

{"total":39,//总记录数

  "rp":10,//每页条数

  "page":1,//当前页

  "ids":["1","2","8","9","10","32","33","65","67","99"],//id列表

  "rows":[["1","P20120806094914","通讯网关服务","192.168.83.226","2013-05-22 17:28:33.053","2013-05-22 17:37:55.21","<span class=\"label label-success\">online<\/span>"],

             ["2","P20100115165302","业务服务","192.168.83.253","2013-02-27 13:37:18.703","2013-02-27 14:03:10.437","<span class=\"label label-warning\">offline<\/span>"],

             ["8","P20130108141508","短信网关","192.168.83.126","2013-05-17 13:33:41.737","2013-05-19 12:08:29.953","<span class=\"label label-warning\">offline<\/span>"],

             ["9","P20130108141459","转发服务","192.168.83.226","2013-03-06 15:29:09.667","2013-03-06 15:34:39.667","<span class=\"label label-success\">online<\/span>"],

             ["10","P20110307164005","接收服务","192.168.83.100","2013-04-07 12:47:22.233","2013-04-08 10:59:22.653","<span class=\"label label-success\">online<\/span>"],

             ["32","P20100115165302","业务服务","192.168.83.253","2013-02-26 08:52:19.843","","<span class=\"label label-success\">online<\/span>"],

             ["33","P20100115165302","业务服务","192.168.83.253","2013-02-26 09:54:31.0","2013-02-26 09:56:56.06","<span class=\"label label-success\">online<\/span>"],

             ["65","P20120806094914","通讯网关服务","192.168.83.253","2013-03-07 11:15:05.26","2013-03-07 14:28:59.073","<span class=\"label label-success\">online<\/span>"],

             ["67","P20100115165302","业务服务","192.168.83.253","2013-04-27 08:59:45.52","2013-04-27 10:56:54.233","<span class=\"label label-success\">online<\/span>"],

             ["99","P20130108141459","转发服务","192.168.83.126","2013-03-06 16:31:44.683","2013-03-06 16:52:22.637","<span class=\"label label-success\">online<\/span>"]

            ]

}


下面是单独封装的分页方法:

/**
 * 
 */
package com.starnet.frame.core.activerecord;

import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.TableInfo;
import com.jfinal.plugin.activerecord.TableInfoMapping;
import com.starnet.frame.core.model.DataTablesModel;

import java.util.*;

/**
 * @author huxiang
 * 
 */
@SuppressWarnings({ "rawtypes" })
public abstract class DbModel<T extends DbModel> extends Model<T> {

	private static final long serialVersionUID = -6215428115177000482L;

	private static final TableInfoMapping tableInfoMapping = TableInfoMapping
			.me();


	/**
	 * 用来针对DataTables封装的分页查询
	 * 
	 * @param pageNumber
	 * @param pageSize
	 * @param select
	 * @param sqlExceptSelect
	 * @param paras
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public DataTablesModel paginateDataTables(int pageNumber, int pageSize,
			String select, String sqlExceptSelect, Object... paras) {

		Page<T> pages = super.paginate(pageNumber, pageSize, select,
				sqlExceptSelect, paras);

		TableInfo tInfo = tableInfoMapping.getTableInfo(getClass());
		List<String> ids = new ArrayList<String>();
		List<List<String>> cells = new ArrayList<List<String>>();
		for (int i = 0; i < pages.getList().size(); i++) {
			T t = pages.getList().get(i);

			Map attrs = t.getAttrs();
			Set<String> key = attrs.keySet();
			List<String> cell = new ArrayList<String>();
			for (Iterator it = key.iterator(); it.hasNext();) {
				String s = (String) it.next();
				if (s.toLowerCase().equals(tInfo.getPrimaryKey().toLowerCase())) {
					ids.add(attrs.get(s).toString());
				} else {
					if (null != attrs.get(s)) {
						cell.add(attrs.get(s).toString());
					} else {
						cell.add("");
					}
				}
			}
			cells.add(cell);

		}

		return new DataTablesModel(pageNumber, pageSize, pages.getTotalRow(),
				ids, cells);
	}

	/**
	 * 用来针对DataTables封装的分页查询
	 * 
	 * @param pageNumber
	 * @param pageSize
	 * @param select
	 * @param sqlExceptSelect
	 * @return
	 */
	public DataTablesModel paginateDataTables(int pageNumber, int pageSize,
			String select, String sqlExceptSelect) {
		return this.paginateDataTables(pageNumber, pageSize, select,
				sqlExceptSelect, new Object[0]);
	}



}

另需要说明的是:原来jfinal的查询返回的字段顺序不是按照查询selcet的顺序。我直接改了jfinal的大小写不敏感工厂类主要可以按照查询的字段顺序获取结果,其实就是改成了LinkedHashSet、LinkedHashMap:

package com.starnet.frame.core.activerecord;

import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;

import com.jfinal.plugin.activerecord.IContainerFactory;

/**
 * 修改了原jfinal的大小写不敏感工厂类,主要可以按照查询的字段顺序获取结果
 * @author huxiang
 *
 */
@SuppressWarnings({"rawtypes", "unchecked"})
public class CaseInsensitiveContainerFactory implements IContainerFactory {

	private static boolean toLowerCase = false;

	public CaseInsensitiveContainerFactory() {
	}

	public CaseInsensitiveContainerFactory(boolean toLowerCase) {
		CaseInsensitiveContainerFactory.toLowerCase = toLowerCase;
	}

	public Map<String, Object> getAttrsMap() {
		return new CaseInsensitiveMap();
	}

	public Map<String, Object> getColumnsMap() {
		return new CaseInsensitiveMap();
	}

	public Set<String> getModifyFlagSet() {
		return new CaseInsensitiveSet();
	}

	private static Object convertCase(Object key) {
		if (key instanceof String)
			return toLowerCase ? ((String) key).toLowerCase() : ((String) key)
					.toUpperCase();
		return key;
	}

	/*
	 * 1:非静态内部类拥有对外部类的所有成员的完全访问权限,包括实例字段和方法,
	 *    为实现这一行为,非静态内部类存储着对外部类的实例的一个隐式引用
	 * 2:序列化时要求所有的成员变量是Serializable 包括上面谈到的引式引用
	 * 3:外部类CaseInsensitiveContainerFactory 需要 implements Serializable 才能被序列化
	 * 4:可以使用静态内部类来实现内部类的序列化,而非让外部类实现 implements Serializable 
	 */
	public static class CaseInsensitiveSet extends LinkedHashSet {

		private static final long serialVersionUID = 102410961064096233L;

		public boolean add(Object e) {
			return super.add(convertCase(e));
		}

		public boolean remove(Object e) {
			return super.remove(convertCase(e));
		}

		public boolean contains(Object e) {
			return super.contains(convertCase(e));
		}
	}

	public static class CaseInsensitiveMap extends LinkedHashMap {

		private static final long serialVersionUID = 6843981594457576677L;

		public Object get(Object key) {
			return super.get(convertCase(key));
		}

		public boolean containsKey(Object key) {
			return super.containsKey(convertCase(key));
		}

		public Object put(Object key, Object value) {
			return super.put(convertCase(key), value);
		}

		public void putAll(Map m) {
			for (Map.Entry e : (Set<Map.Entry>) (m.entrySet()))
				put(e.getKey(), e.getValue());
		}

		public Object remove(Object key) {
			return super.remove(convertCase(key));
		}
	}
}

最后非常感谢jfinal,也谢谢分享开源的开发者。


你可能感兴趣的:(jFinal,datatables)