目前市面上N多前台技術展現樹形結構,最簡單的莫過於Dtree,但是對於實現比較複雜的帶各種控制項的樹,還是jquery ext dhtmlx等js小架構略勝一籌,而這些架構,幾乎無一例外支援json格式的資料當作樹的資料來源。json 是個好東西啊,瞭解它 請參看這個網站
Json介紹 各個平台的開發人員都可以在上面找到協助。個人最近被派去做前台開發,做了個授權的菜單授權的功能,很常用的功能。於是寫了個工具類,用於將有父子關係的集合類轉換成json格式字串,用於前台展示,沒怎麼最佳化和重構,有需要大家自己改改,呵呵。
package com.**.util;/** * 將具有樹形資料庫記錄轉換成樹形json格式資料,供前台展現成樹狀使用 * @author youjianbo 2011-08-04 youjianbo_han_87@hotmail.com * */import java.util.ArrayList;import java.util.Iterator;import java.util.List;public class JsonUtils { StringBuffer json = new StringBuffer(); List tempList = new ArrayList(); /** * 構建Json檔案 * * @param list * @param node */ private String constructorJson(List list, TreeNode treeNode) { if (hasChild(list, treeNode)) { json.append("{\"id\":\""); json.append(treeNode.getNodeId() + "\""); json.append(",\"text\":\""); json.append(treeNode.getNodename() + "\""); if (treeNode.getNodeCode().length() < 2) { json.append(",\"state\":\"opened\""); } else { json.append(",\"state\":\"closed\""); } if ("0".equals(treeNode.getNodeId())) { json.append(",\"iconCls\":\"icon-monitor\""); } else { json.append(",\"iconCls\":\"icon-phonebook\""); } json.append(",\"children\":["); tempList.add(treeNode); List childList = getChildList(list, treeNode); Iterator iterator = childList.iterator(); while (iterator.hasNext()) { TreeNode node = (TreeNode) iterator.next(); constructorJson(list, node); } json.append("]},"); } else { json.append("{\"id\":\""); json.append(treeNode.getNodeId() + "\""); json.append(",\"text\":\""); json.append(treeNode.getNodename() + "\""); json.append("},"); tempList.add(treeNode); } return json.toString(); } /** * 獲得子節點列表資訊 * * @param list * @param node * @return */ private List getChildList(List list, TreeNode node) { // 得到子節點列表 List li = new ArrayList(); Iterator it = list.iterator(); while (it.hasNext()) { TreeNode n = (TreeNode) it.next(); if (n.getFather_nodeId().equals(node.getNodeId()) && !n.getFather_nodeId().equals(n.getNodeId())) { li.add(n); } } return li; } /** * 判斷是否有子節點 * * @param list * @param node * @return */ private boolean hasChild(List list, TreeNode node) { return getChildList(list, node).size() > 0 ? true : false; } /** * 取得單個節點及其子節點JSON格式字串 * */ public String getJson(List list, TreeNode node) { json = new StringBuffer(); constructorJson(list, node); String jsonDate = json.toString(); return jsonDate.replaceAll(",]", "]"); } /** * 取得多個節點及其子節點JSON格式字串 * */ public String getJson(List list) { tempList = new ArrayList(); json = new StringBuffer(); Iterator iterator = list.iterator(); while (iterator.hasNext()) { TreeNode node = (TreeNode) iterator.next(); if (!tempList.contains(node)) { constructorJson(list, node); } } String jsonDate = json.toString(); return ("[" + jsonDate + "]").replaceAll(",]", "]"); }}
個人用jquery easy ui 展示tree 時,貌似發現一個bug。文章地址:http://topic.csdn.net/u/20110822/14/9afd5459-6108-48af-bc54-e0365d9f824f.html
有問題的樣本:http://download.csdn.net/source/3541195。個人對前台開發實在不熟,目前也沒時間細看jquery,有空的朋友,幫忙看看。解決了就留給言,謝謝哈。