递归调用是一种强大的嵌套循环方式,它可以在递归过程中按照条件和参数完成其他循环语句无法完成的工作,比如动态组建有规律的字符串等。
最近在使用Extjs4做一个网站的后台管理系统,用户登录成功后,页面左边要显示一个该用户的可操作菜单列表,这里要用到Extjs tree组建来实现。tree组建支持同步和异步两种方式用JSON来组建树节点,对于多用户系统,每个用于的权限分配不一样,左边显示出来的可操作菜单也就不一样,这样一来,左边的树菜单节点只能动态加载了,也就是用Extjs的Ajax能力从服务器获得节点信息的JSON字符串来构建树菜单。
一个简单的Tree Node的JSON字符串:
1
2
|
[{
"children"
:[{
"children"
:[],
"cls"
:
"file"
,
"id"
:11,
"leaf"
:
true
,
"text"
:
"子菜单1-1"
},{
"children"
:[],
"cls"
:
"file"
,
"id"
:12,
"leaf"
:
true
,
"text"
:
"子菜单1-2"
}],
"cls"
:
"folder"
,
"id"
:10,
"leaf"
:
false
,
"text"
:
"二级菜单目录1"
},{
"children"
:[{
"children"
:[],
"cls"
:
"file"
,
"id"
:21,
"leaf"
:
true
,
"text"
:
"子菜单2-1"
},{
"children"
:[],
"cls"
:
"file"
,
"id"
:22,
"leaf"
:
true
,
"text"
:
"子菜单2-2"
}],
"cls"
:
"folder"
,
"id"
:20,
"leaf"
:
false
,
"text"
:
"二级菜单目录2"
}]
|
但是如果节点数据是从数据库里读取出来的,在java处理类里怎么去构建这个字符串呢?
这里,如果使用while或者for循环的方式,不可取,因为不知道节点的深度,要嵌套多少层。如果知道节点的深度并写死在处理类里,也降低了程序的智能化程度,一旦修改了节点数据,程序里也要做相应的修改,也不可取。
其实,办法总是有的,语言是无所不能的。在这里可以写一个递归方法,根据节点在数据库里的id标识获取其所有的下级节点组建JSON字符串并返回。
实现相关源码:
数据库tree节点数据(本设计考虑到其他比如JQuery、DTree等AJAX框架的兼容,树节点数据库表设计采用了通用的模式):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
#菜单表
create
table
sys_menu
(
menu_id
int
auto_increment
primary
key
, #菜单编号
menu_title
varchar
(50)
not
null
, #菜单文本
menu_level
int
not
null
, #菜单级别
menu_superior
int
default
-1
not
null
, #父菜单编号
menu_url
varchar
(500)
not
null
#指定URL
);
insert
into
sys_menu
values
(
null
,
'系统管理'
,1,-1,
''
);
insert
into
sys_menu
values
(
null
,
'用户管理'
,2,1,
'mgr/pages/user_mgr.html'
);
insert
into
sys_menu
values
(
null
,
'修改密码'
,2,1,
'mgr/pages/pwd_modify.html'
);
insert
into
sys_menu
values
(
null
,
'友情链接'
,2,1,
'mgr/pages/link_mgr.html'
);
|
tree菜单节点查询并组装成JSON字符串的java递归方法(类)源码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
|
package
util;
import
java.util.Map;
import
java.util.List;
import
access.DB;
public
class
TreeBuild {
private
static
String buildTreeJSON(
int
nodeId,
int
c){
Map<String, Object> node = DB.query(
"select * from sys_menu where menu_id="
+nodeId).get(
0
);
String ss =
""
;
String sql =
"select * from sys_menu where menu_superior="
+nodeId;
List<Map<String, Object>> nodes = DB.query(sql);
if
(nodes!=
null
&& nodes.size()>
0
){
ss +=
"{\"children\":["
;
int
cc = nodes.size();
for
(Map<String, Object> n:nodes){
ss += buildTreeJSON(Integer.parseInt(n.get(
"menu_id"
).toString()),cc);
cc--;
}
ss +=
"],\"cls\":\"folder\",\"id\":"
+node.get(
"menu_id"
)+
",\"leaf\":false,\"text\":\""
+node.get(
"menu_title"
)+
"\"}"
;
}
else
{
ss +=
"{\"children\":[],\"cls\":\"file\",\"id\":"
+node.get(
"menu_id"
)+
",\"leaf\":true,\"text\":\""
+node.get(
"menu_title"
)+
"\"}"
;
}
if
(c>
1
){
ss +=
","
;
}
return
ss;
}
public
static
String getTree(
int
[] par){
String ss =
"["
;
int
c = par.length;
for
(
int
nodeId:par){
ss+=buildTreeJSON(nodeId,c);
c--;
}
String es =
"]"
;
return
ss+es;
}
}
|
调用时,调用本类的getTree方法,传入几个根节点的id标识,该方法会自动完成JSON字符串的最组装,并返回组装好的JSON字符串。Ext UI端直接用AJAX调用该JSON返回控制器URL即可。
另外一种很强大的方法(将Tree Node用Java对象封装起来,然后再将对象转换成JSON字符串,这种方式应该用得最多):
效果截图:
在线Demo: freedomsmile.net/Ext_Demo (打开有点慢,JS文件1MB多)
Google code svn: http://photon86.googlecode.com/svn/trunk
本例war包: Ext_Demo 2.53MB (运行环境:JRE1.6,Tomcat6)
下面贴出实现代码:
- /********************************* Tree Begin ************************************/
- var treeStore = Ext.create("Ext.data.TreeStore",{
- proxy : {
- type : "ajax",
- url : "BaseAction?method=getTreeData"
- },
- nodeParam : "id" //设置传递给后台的参数名,值是树节点的id属性
- });
- Ext.create("Ext.tree.Panel", {
- renderTo: 'left',
- width: '100%',
- height: '100%',
- title : "开发技术",
- rootVisible : true, //显示根节点
- root: {
- id: 'root',
- text: '根节点',
- expanded: false,
- leaf: false
- },
- viewConfig : {
- loadingText : "加载数据..."
- },
- store : treeStore
- });
- /**************************** Tree End ********************************/
数据实体类(Technology.java):
- package com.demo.entity;
- public class Technology{
- private String id; //主键ID
- private String name; //技术名称
- private String pid; //父ID
- public String getId(){
- return id;
- }
- public void setId(String id){
- this.id = id;
- }
- public String getName(){
- return name;
- }
- public void setName(String name){
- this.name = name;
- }
- public String getPid(){
- return pid;
- }
- public void setPid(String pid){
- this.pid = pid;
- }
- }
树节点实体对象(TreeNode.java),主要作用是简化前端Javascript编码,直接返回tree需要的数据格式,所以此类中定义的关键属性必须跟ExtJS API定义的一样,比如:id、text、leaf。如果是ajax异步加载数据,每次加载一级数据,则不需要递归,也就不需要属性:private List<TreeNode> children = new ArrayList<TreeNode>();,否则不显示加号,无法加载子节点。当某一级数据已经加载,第二次展开的时候不会重复请求后台,这点Ext做得好。
- package com.demo.entity;
- public class TreeNode{
- private String id;
- private String text;
- private Boolean leaf = true; //是否子叶子节点,默认是
- private String cls; //图标
- private String iconCls;
- private String action; //请求路径
- private String model;
- private Boolean expanded; //展开
- //private List<TreeNode> children = new ArrayList<TreeNode>();
- public String getId(){
- return id;
- }
- public void setId(String id){
- this.id = id;
- }
- public String getText(){
- return text;
- }
- public void setText(String text){
- this.text = text;
- }
- public Boolean getLeaf(){
- return leaf;
- }
- public void setLeaf(Boolean leaf){
- this.leaf = leaf;
- }
- public String getCls(){
- return cls;
- }
- public void setCls(String cls){
- this.cls = cls;
- }
- public String getIconCls(){
- return iconCls;
- }
- public void setIconCls(String iconCls){
- this.iconCls = iconCls;
- }
- public String getAction(){
- return action;
- }
- public void setAction(String action){
- this.action = action;
- }
- public String getModel(){
- return model;
- }
- public void setModel(String model){
- this.model = model;
- }
- public Boolean getExpanded(){
- return expanded;
- }
- public void setExpanded(Boolean expanded){
- this.expanded = expanded;
- }
- // public List<TreeNode> getChildren(){
- // return children;
- // }
- // public void setChildren(List<TreeNode> children){
- // this.children = children;
- // }
- }
测试数据(TreeAction.java),为简化操作,暂时未用数据库。大概想了下,如果用数据库,也是异步加载子节点,那最好在实体类Technology里封装一个 leaf 属性,代表此Technology是否为叶子节点,这样的好处是封装TreeNode对象的时候方便判断 leaf 的值,少查询一次数据库,但记得每次修改节点的时候同时更新 leaf 。
- package com.demo.action;
- import java.io.PrintWriter;
- import java.util.ArrayList;
- import java.util.List;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import com.demo.entity.Technology;
- import com.demo.entity.TreeNode;
- import net.sf.json.JSONArray;
- @SuppressWarnings("unchecked")
- public class TreeAction{
- public void getTreeData(HttpServletRequest request, HttpServletResponse response){
- try{
- String id = request.getParameter("id");
- //System.out.println("父节点ID:" + id);
- List<Technology> list = TreeData();
- List<TreeNode> tn = new ArrayList<TreeNode>();
- if(id == null || id.equals("root")){
- for(Technology t : list){
- if(t.getPid().equals("0")){
- TreeNode treeNode = new TreeNode();
- treeNode.setId(t.getId());
- treeNode.setText(t.getName());
- treeNode.setLeaf(false);
- tn.add(treeNode);
- }
- }
- }else{
- for(Technology t : list){
- if(t.getPid().equals(id)){
- TreeNode treeNode = new TreeNode();
- treeNode.setId(t.getId());
- treeNode.setText(t.getName());
- tn.add(treeNode);
- for(Technology te : list){
- if(t.getId().equals(te.getPid())){
- treeNode.setLeaf(false);
- }
- }
- }
- }
- }
- JSONArray ja = JSONArray.fromObject(tn);
- //System.out.println(ja);
- PrintWriter out = response.getWriter();
- out.print(ja.toString());
- }catch(Exception e){
- e.printStackTrace();
- }
- }
- public List<Technology> TreeData(){
- List<Technology> list = new ArrayList<Technology>();
- Technology t1 = new Technology();
- t1.setId("1");
- t1.setName("前端");
- t1.setPid("0");
- list.add(t1);
- Technology t2 = new Technology();
- t2.setId("2");
- t2.setName("后端");
- t2.setPid("0");
- list.add(t2);
- Technology t3 = new Technology();
- t3.setId("3");
- t3.setName("C");
- t3.setPid("2");
- list.add(t3);
- Technology t4 = new Technology();
- t4.setId("4");
- t4.setName("C#");
- t4.setPid("2");
- list.add(t4);
- Technology t5 = new Technology();
- t5.setId("5");
- t5.setName("Java");
- t5.setPid("2");
- list.add(t5);
- Technology t6 = new Technology();
- t6.setId("6");
- t6.setName("PHP");
- t6.setPid("2");
- list.add(t6);
- Technology t7 = new Technology();
- t7.setId("7");
- t7.setName("Servlet");
- t7.setPid("5");
- list.add(t7);
- Technology t8 = new Technology();
- t8.setId("8");
- t8.setName("JSP");
- t8.setPid("5");
- list.add(t8);
- Technology t9 = new Technology();
- t9.setId("9");
- t9.setName("Struts");
- t9.setPid("5");
- list.add(t9);
- Technology t10 = new Technology();
- t10.setId("10");
- t10.setName("Spring");
- t10.setPid("5");
- list.add(t10);
- Technology t11 = new Technology();
- t11.setId("11");
- t11.setName("Hibernate");
- t11.setPid("5");
- list.add(t11);
- Technology t12 = new Technology();
- t12.setId("12");
- t12.setName("HTML");
- t12.setPid("1");
- list.add(t12);
- Technology t13 = new Technology();
- t13.setId("13");
- t13.setName("JavaScript");
- t13.setPid("1");
- list.add(t13);
- Technology t14 = new Technology();
- t14.setId("14");
- t14.setName("CSS");
- t14.setPid("1");
- list.add(t14);
- Technology t15 = new Technology();
- t15.setId("15");
- t15.setName("Session");
- t15.setPid("11");
- list.add(t15);
- Technology t16 = new Technology();
- t16.setId("16");
- t16.setName("SessionFactory");
- t16.setPid("11");
- list.add(t16);
- Technology t17 = new Technology();
- t17.setId("17");
- t17.setName("Transaction");
- t17.setPid("11");
- list.add(t17);
- Technology t18 = new Technology();
- t18.setId("18");
- t18.setName("Query");
- t18.setPid("11");
- list.add(t18);
- Technology t19 = new Technology();
- t19.setId("19");
- t19.setName("Criteria");
- t19.setPid("11");
- list.add(t19);
- Technology t20 = new Technology();
- t20.setId("20");
- t20.setName("Configuration");
- t20.setPid("11");
- list.add(t20);
- return list;
- }
- }
servlet(BaseAction.java),负责跳转,调用对应方法:
- package com.demo.action;
- import java.io.IOException;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import com.demo.action.GridAction;
- import com.demo.action.TreeAction;
- @SuppressWarnings("unchecked")
- public class BaseAction extends HttpServlet{
- private static final long serialVersionUID = 1L;
- public BaseAction(){
- super();
- }
- public void destroy(){
- super.destroy();
- }
- public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
- response.setContentType("text/html;charset=utf-8");
- GridAction ga = new GridAction();
- TreeAction ta = new TreeAction();
- String method = request.getParameter("method");
- if(method != null){
- if(method.equals("getGridData")){
- ga.getGridData(request, response);
- }else if(method.equals("getTreeData")){
- ta.getTreeData(request, response);
- }else{
- //404
- }
- }else{
- //404
- }
- }
- public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
- doGet(request, response);
- }
- public void init() throws ServletException{}
- }
Tree所需JSON数组格式:
- [
- {
- "action": "",
- "cls": "",
- "expanded": false,
- "iconCls": "",
- "id": "1",
- "leaf": false,
- "model": "",
- "text": "前端"
- },
- {
- "action": "",
- "cls": "",
- "expanded": false,
- "iconCls": "",
- "id": "2",
- "leaf": false,
- "model": "",
- "text": "后端"
- }
- ]