后台管理系统的树形菜单是非常常见的一个功能,今天我就把自己工作中所写的简单代码贴一下,希望对一些网友有帮助。首先创建一个菜单数据表:
CREATE TABLE `resources` (`id` int(11) NOT NULL AUTO_INCREMENT,`parentId` int(11) DEFAULT '0' COMMENT '父ID',`name` varchar(30) NOT NULL COMMENT '菜单名称',`resourceDesc` varchar(100) NOT NULL COMMENT '描述',`resourceStr` varchar(100) DEFAULT NULL COMMENT '菜单字符串',`enabled` tinyint(1) DEFAULT NULL COMMENT '是否有效',`issys` tinyint(1) DEFAULT NULL COMMENT '是否为系统菜单',`module` varchar(20) DEFAULT '' COMMENT '模块',`icon` varchar(20) DEFAULT '' COMMENT '图标',`imgUrl` varchar(255) DEFAULT '' COMMENT '图片存储路径',`resouceType` varchar(10) NOT NULL DEFAULT 'menu' COMMENT '资源类型: menu 菜单, button 按钮', PRIMARY KEY (`id`)) ENGINE=MyISAM AUTO_INCREMENT=283 DEFAULT CHARSET=utf8 COMMENT='后台菜单表'
实体类Resources
package com.lxh;
import java.util.List;
/**
* 菜单
*/
public class Resources {
private Integer id;
/**
* 菜单名
*/
private String name;
/**
* 菜单描述
*/
private String resourceDesc;
/**
* 菜单url
*/
private String resourceStr;
private String module;
/**
* 是否有效
*/
private Boolean enabled;
/**
* 是否系统菜单
*/
private Boolean issys;
private String icon;
/**
* 排序
*/
private int order;
private String imgUrl;
// 所属模块
private String moduleName;
private String resouceType;
private Integer parentId;
private Integer sortOrder; // 排列顺序
private Integer isShow; // 是否显示1显示;2隐藏
private Integer level; // 级别
private List<Resources> resources;
public Integer getId() {
return id;
}
public Integer getSortOrder() {
return sortOrder;
}
public void setSortOrder(Integer sortOrder) {
this.sortOrder = sortOrder;
}
public Integer getIsShow() {
return isShow;
}
public void setIsShow(Integer isShow) {
this.isShow = isShow;
}
public Integer getLevel() {
return level;
}
public void setLevel(Integer level) {
this.level = level;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getResourceDesc() {
return resourceDesc;
}
public void setResourceDesc(String resourceDesc) {
this.resourceDesc = resourceDesc;
}
public String getResourceStr() {
return resourceStr;
}
public void setResourceStr(String resourceStr) {
this.resourceStr = resourceStr;
}
public Boolean getEnabled() {
return enabled;
}
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
public Boolean getIssys() {
return issys;
}
public void setIssys(Boolean issys) {
this.issys = issys;
}
public String getModule() {
return module;
}
public void setModule(String module) {
this.module = module;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public int getOrder() {
return order;
}
public void setOrder(int order) {
this.order = order;
}
public String getImgUrl() {
return imgUrl;
}
public void setImgUrl(String imgUrl) {
this.imgUrl = imgUrl;
}
public String getModuleName() {
return moduleName;
}
public void setModuleName(String moduleName) {
this.moduleName = moduleName;
}
public String getResouceType() {
return resouceType;
}
public void setResouceType(String resouceType) {
this.resouceType = resouceType;
}
public Integer getParentId() {
return parentId;
}
public void setParentId(Integer parentId) {
this.parentId = parentId;
}
public List<Resources> getResources() {
return resources;
}
public void setResources(List<Resources> resources) {
this.resources = resources;
}
}
生成菜单树的简单算法
package com.lxh;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ResourceTree {
public void testQueryResourcesList(List<Resources> list) {
List<Resources> rootResources = list;
List<Resources> menuList = new ArrayList<Resources>();
// 先找到所有的一级菜单
for (int i = 0; i < rootResources.size(); i++) {
// 一级菜单没有parentId
if (rootResources.get(i).getParentId()==0) {
menuList.add(rootResources.get(i));
}
}
// 为一级菜单设置子菜单,getChild是递归调用的
for (Resources menu : menuList) {
menu.setResources(getChild(menu.getId(), rootResources));
}
Map<String, Object> jsonMap = new HashMap<>();
jsonMap.put("menu", menuList);
}
/**
* 递归查找子菜单
*
* @param id 当前菜单id
* @param rootResources 要查找的列表
* @return
*/
private List<Resources> getChild(int id, List<Resources> rootResources) {
// 子菜单
List<Resources> childList = new ArrayList<>();
for (Resources menu : rootResources) {
// 遍历所有节点,将父菜单id与传过来的id比较
if (menu.getParentId()!=null) {
if (menu.getParentId()==id) {
childList.add(menu);
}
}
}
//查找子菜单是否有子菜单
for (Resources menu : childList) {
menu.setResources(getChild(menu.getId(), rootResources));
}
// 递归退出条件
if (childList.size() == 0) {
return null;
}
return childList;
}
}
测试工具
package com.lxh;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
public class MysqlHelper {
// 加载驱动
private final String DRIVER = "com.mysql.jdbc.Driver";
// 定义数据库账号
private final String USERNAME = "develop";
// 定义数据库密码
private final String PASSWORD = "";
// 访问的地址
private final String URL = "jdbc:mysql://10.50.10.202:3306/hhn_user";
// 定义数据库的连接
private Connection connection;
// 定义sql语句的执行对象
private PreparedStatement pStatement;
// 定义查询返回的结果集合
private ResultSet resultset;
private final static Map<String, String> purchaseMap=new HashMap<String, String>();
public MysqlHelper() {
try {
Class.forName(DRIVER);// 注册驱动
connection = (Connection) DriverManager.getConnection(URL, USERNAME, PASSWORD);// 定义连接
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
MysqlHelper help = new MysqlHelper();
List<Resources> list= help.query();
TreeGrid treeGrid = new TreeGrid(list);
TreeMenu treemenu = treeGrid.getTreeMenu();
List<TreeMenu> l = treemenu.getChildren();
for(TreeMenu t:l){
System.out.println(t.getName()+"——"+t.getId()+"——"+t.getParentId());
}
new ResourceTree ().testQueryResourcesList(list);
}
public Resources getreeNode(int cid){
String sql = " select * from resources WHERE module='customer' and id = "+cid;
PreparedStatement pstmt;
Resources res = new Resources();
try {
pstmt = (PreparedStatement) connection.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
res.setId(rs.getInt(1));
res.setName(rs.getString(2));
res.setResourceDesc(rs.getString(3));
}
} catch (SQLException e) {
e.printStackTrace();
}
return res;
}
public List<Resources> query(){
String sql = " select id,parentId,name from resources WHERE module='customer' ";
PreparedStatement pstmt;
List<Resources> tempList = new ArrayList<Resources>();
try {
pstmt = (PreparedStatement) connection.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
Resources res = new Resources();
res.setId(rs.getInt(1));
res.setParentId(rs.getInt(2));
res.setName(rs.getString(3));
tempList.add(res);
}
} catch (SQLException e) {
e.printStackTrace();
}
return tempList;
}
public static void test(MysqlHelper help){
String sql = "ALTER TABLE p_fund_user_account_log ADD `orderSource` tinyint(4) DEFAULT '0' COMMENT '订单渠道' after channel;";
for (int i = 0; i < 100; i++) {
String temp = "";
if (i < 10) {
temp = "p_fund_user_account_log_0" + i;
} else {
temp = "p_fund_user_account_log_" + i;
}
temp=sql.replace("p_fund_user_account_log", temp);
System.out.println(temp);
}
}
public void test1(MysqlHelper help){
String sql = " alter table `trade_order` drop column source";
for (int i = 0; i < 100; i++) {
String temp = "";
if (i < 10) {
temp = "trade_order_0" + i;
} else {
temp = "trade_order_" + i;
}
temp=sql.replace("trade_order", temp);
System.out.println(temp);
try {
help.addDeleteModify(temp, null);
} catch (SQLException e) {
e.printStackTrace();
}
}
try {
System.out.println(sql);
help.addDeleteModify(sql, null);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 完成对数据库的增删改操作
*
* @param sql语句
* @param 传入的占位符,List集合
* @return SQL语句执行成功返回true,否则返回false
* @throws SQLException
*/
public boolean addDeleteModify(String sql, List<Object> params) throws SQLException {
int result = -1;// 设置为
pStatement = (PreparedStatement) connection.prepareStatement(sql); // 填充占位符
int index = 1; // 从第一个开始添加
if (params != null && !params.isEmpty()) {
for (int i = 0; i < params.size(); i++) {
pStatement.setObject(index++, params.get(i));// 填充占位符
}
}
result = pStatement.executeUpdate();// 执行成功将返回大于0的数
return result > 0 ? true : false;
}
/**
* 注意在finally里面执行以下方法,关闭连接
*/
public void closeconnection() {
if (resultset != null) {
try {
resultset.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (pStatement != null) {
try {
pStatement.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}