package com.bonus.sys; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.StringUtils; import com.bonus.sys.beans.ResourcesBean; public class MenuTreeHelper { /** * 建立树菜单 * * @param menusDB * 菜单集合(不是树) * @return 有样式的树的html字符串 */ public static String buildTreeHtml(List menusDB) { StringBuffer html = new StringBuffer(); for (int i = 0; i < menusDB.size(); i++) { ResourcesBean node = menusDB.get(i); if ("0".equals(node.getParentId())) { boolean childrenHas = false; List children = getChildren(menusDB, node); if (!children.isEmpty()) childrenHas = true; if (i == 0) { html.append("\r\n"); } } return html.toString(); } private static void build(List menusDB, ResourcesBean node, StringBuffer html) { List children = getChildren(menusDB, node); if (!children.isEmpty()) { html.append("\r\n"); } } private static List getChildren(List menusDB, ResourcesBean node) { List children = new ArrayList(); String id = node.getId()+""; for (ResourcesBean child : menusDB) { if (id.equals(child.getParentId())) { children.add(child); } } return children; } /** * 建立树菜单 * * @param menusDB * 菜单集合(不是树) * @return 有样式的树的菜单集合 */ public static List buildTree(List menusDB) { List res = new ArrayList(); for (ResourcesBean node : menusDB) { if ("0".equals(node.getParentId())) { List children = getChildren(menusDB, node); node.setNodes(children); build(menusDB, node, res); res.add(node); } } return res; } private static void build(List menusDB, ResourcesBean node, List res) { List children = getChildren(menusDB, node); if (!children.isEmpty()) { for (ResourcesBean child : children) { List children2 = getChildren(menusDB, child); child.setNodes(children2); build(menusDB, child, res); } } } }