背景:最近用ExtJS4.2做一个系统,需要在前端展示资源菜单,为树形结构,该树形结构是从数据库动态加载的。
ExtJS的树形结构大致有两种情况:
1.静态树形结构,此处不多说,看API就能简单明白;
2.动态加载,ExtJS的特性是根据父节点ID来查询子节点,从而动态更新树形菜单,这里有一个缺陷,或许是我孤陋寡闻不知道,那就是无法根据数据库节点信息自动构建成为一棵树,记得zTree插件就有这个功能。
那么,我希望能够根据数据库树节点信息自动的构建成一棵树,就需要自己去写个小算法在后台拼接成ExtJS需要的数据结构。
代码部分:
1.节点pojo,必要属性有:节点ID(id)、父节点ID(parentId)、文本信息(text)、孩子(children),其他属性,比如节点url,顺序order等根据自己需要设置。
public class Resource { private Integer id; private String text; private Integer parentId; private Boolean expanded; private Listchildren = new ArrayList (); }
2.根据查询出来的节点List集合拼装成为前端展示需要的结构,这里写了个静态方法。
public static finalList buildTree(List nodes) { if(null == nodes || nodes.size() == 0) return null; Map resources = new HashMap (); List result = new ArrayList (); try { for(int i=0; i e : resources.entrySet()) { T node = e.getValue(); Method getparentId = node.getClass().getMethod("getParentId"); Integer parentId = (Integer) getparentId.invoke(node); if(parentId == 0) { result.add(node); } else { T parent = resources.get(parentId); if( null != parent) { @SuppressWarnings("unchecked") List children = (List ) parent.getClass().getMethod("getChildren").invoke(parent); children.add(node); } } } } catch (Exception e) { e.printStackTrace(); } return result; }
3.数据库记录。
4.ExtJS前端代码。
Ext.onReady(function() { var store = Ext.create('Ext.data.TreeStore', { proxy: { type: 'ajax', url: 'your url' }, root: { text: '系统菜单', id: 0, expanded: true } }); var treePanel = Ext.create('Ext.tree.Panel', { title: '树形菜单', width: 300, height: 350, margin: '50 0 0 500', store: store, rootVisible: false, useArrows: true, renderTo: Ext.getBody() });});
5.效果图。
6.完毕。