目前市面上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,有空的朋友,帮忙看看。解决了就留给言,谢谢哈。