来源:http://3ccoder.iteye.com/blog/556668
作者:yadsun
服务器端方法
public File writeJason(){
final List<ADAuthority> allMenus = securityManager.getUserMenuTree(); //根据用户ID从数据库读出用户的所有权限
final List<ADAuthority> leafs = new LinkedList<ADAuthority>(allMenus);//有顺序的list
List<ADAuthority> roots = new LinkedList<ADAuthority>();//把所有根节点取出,这里的根不是Ext.tree.TreePanel里的root而是它的一级子节点
for (ADAuthority menu : allMenus) {
if (menu.getLevel() == 1) {
roots.add(menu);
leafs.remove(menu);
}
}
List<Map<ADAuthority, List>> results = new LinkedList();
for(ADAuthority root : roots){
Map<ADAuthority,List> m = getDeepChildren(root, leafs);
results.add(m);
}
String s = Map2Json(results);
//将s写入服务器端.json文件
}
/*
* 递归方法
* 传一个根节点和其他所有节点的集合
* 根据根结点遍历其下的所有子结点
*/
public static Map<ADAuthority,List> getDeepChildren(ADAuthority root, List<ADAuthority> leafs){
Map<ADAuthority,List> singleTree = new HashMap<ADAuthority,List>();//用来存放根和其下所有的子
List<Map<ADAuthority,List>> singleLeafs = new LinkedList<Map<ADAuthority,List>>();
List<ADAuthority> copyLeafs = new LinkedList<ADAuthority>(leafs);
for(ADAuthority leaf : leafs){
if (leaf.getParentRrn() == null){
copyLeafs.remove(leaf);
continue;
} else if(leaf.getParentRrn().equals(root.getObjectRrn())){
copyLeafs.remove(leaf);
singleLeafs.add(getDeepChildren(leaf,copyLeafs));
}
}
singleTree.put(root, singleLeafs);
return singleTree;
}
/*
* 递归方法
* 将生成的特定List转成json格式数据
*/
public static String Map2Json(List<Map<ADAuthority, List>> source){
StringBuffer sb = new StringBuffer();
int time = 0;
for(Map<ADAuthority, List> tree : source){
for(ADAuthority key : tree.keySet()){
List<Map<ADAuthority,List>> l = tree.get(key);
if(time++ > 0) sb.append(",");//json的格式,用","分隔每一组{},最后面的一组没有","
sb.append("{'text': '" + key.getLabel_zh() + "',");
sb.append("'cls': 'floder'");
if(l.size() != 0){
sb.append(",'children': [" + Map2Json(l) + "]");
}else{
sb.append(",'leaf': true");
}
sb.append("}");
}
}
return sb.toString();
}
menutree.html内容
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<!--引入ext样式表-->
<link rel="stylesheet" type="text/css" href="../extjs/resources/css/ext-all.css" />
<!--引入ext适配器脚本-->
<script type="text/javascript" src="../extjs/adapter/ext/ext-base.js"></script>
<!--引入ext框架脚本-->
<script type="text/javascript" src="../extjs/ext-all-debug.js"></script>
<script type="text/javascript" src="../js/tree.js"></script>
<title>Tree of ExtJS</title>
</head>
<body>
<div id="menu"></div>
</body>
</html>
menutree.js内容
Ext.onReady(function(){ var tree = new Ext.tree.TreePanel({ renderTo: 'menu', useArrows: true, autoScroll: true, animate: true, enableDD: true, containerScroll: true, border: false, root: { text:'Function List', nodeType: 'async', draggable: false, id: 'source' }, rootVisible:true, // auto create TreeLoader dataUrl: '../js/nodes.json' }); tree.getRootNode().expand(true); });