根据对象,构建tree树形菜单(dhtmlxtree)

在数据库中建立表

t_navgation

id--序号,

name--名称

nav_url--地址

//

remark--备注

isstop--是否停用

 

java 建立对应bean,这里不操作数据库,只是模拟下(实际根据你数据库来操作,生成对应树形菜单)

package com.model;

 

/**
 * 栏目菜单栏----
 * @author Ken Huang
 *
 */
public class NavBean {

 private int id;
 private int parentid;
 private String resourename;
 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 public int getParentid() {
  return parentid;
 }
 public void setParentid(int parentid) {
  this.parentid = parentid;
 }
 public String getResourename() {
  return resourename;
 }
 public void setResourename(String resourename) {
  this.resourename = resourename;
 }
 
}

package com.model;

import java.util.ArrayList;
import java.util.List;

 

/**
 * 通过构造树形栏目
 * 分析:
 * 递归的思想来进行数据传送
 * @author cong *
 */


public class TreeBean {

 public TreeBean(){}
 
 private int id;
 private String text;
 private List item=new ArrayList();
 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 public String getText() {
  return text;
 }
 public void setText(String text) {
  this.text = text;
 }
 public List getItem() {
  return item;
 }
 public void setItem(List item) {
  this.item = item;
 }
 
 
 
 public TreeBean(NavBean node,List<NavBean> navlist)
 {
  this.id=node.getId();
  this.text=node.getResourename();
    NavBean mode=null;
    for(NavBean nodes:navlist)
    {
     if(nodes.getId()==id)
     {
      mode=nodes;
      break;
     }
    }
  
      navlist.remove(mode);
      List<NavBean> children=getChirdlist(mode.getId(), navlist);
      if(children.size()>0)
      {
       for(NavBean child:children)
       {
        
        TreeBean beanchild=new TreeBean(child,navlist);
        this.item.add(child);
       }
      }
  
  
 }
 
 
 private List<NavBean> getChirdlist(int parentId,List<NavBean> list)
 {
  List<NavBean> childlist=new ArrayList<NavBean>();
            for(NavBean childnode :list)
            {
             if(parentId==childnode.getParentid())
             {
              childlist.add(childnode);
             }
            }
            return childlist;
 }
 
 
}


测试:

package com.tree;

import java.util.List;

import com.model.NavBean;
import com.model.NavBeanService;
import com.model.TreeBean;
import net.sf.json.JSONObject;
public class TreeTest {

 /**
  * @param args
  */
 public static void main(String[] args) {
  NavBeanService service=new NavBeanService();
  List<NavBean> lists=service.serach();
  NavBean node=lists.get(0);
  TreeBean tree=new TreeBean(node,lists);
  System.out.println(tree.getItem().size());
  JSONObject json=JSONObject.fromObject(tree);
  System.out.println(json);
  
 }

}

 

结果输出:



 

 

 

 

 

----------如有更好思路或想法,请留言评论下,谢谢。希望通过交流,让大家进步

 

 

你可能感兴趣的:(html)