返回的数据格式如下
"status": 1,
"info": "请求成功",
-"data": [
-{
"menuId": 1,
"parentId": 0,
"name": "系统管理",
"url": null,
"perms": null,
"type": 0,
"icon": "system",
"orderNum": 0,
"roleId": 1,
"sMenuId": 1,
-"childList": [
-{
"menuId": 2,
"parentId": 1,
"name": "管理员列表",
"url": "sys/user",
"perms": null,
"type": 1,
"icon": "admin",
"orderNum": 1,
"roleId": 1,
"sMenuId": 2,
-"childList": [
-{
"menuId": 8,
"parentId": 2,
"name": "新增",
"url": null,
"perms": "sys:schedule:save",
"type": 2,
"icon": null,
"orderNum": 0,
"roleId": 1,
"sMenuId": 8,
"childList": null
}
]
}
实现代码
//层级获取菜单
public List<MenuEntity> hierarchicalAccessMenu(String roleId){
//获取该角色下所有菜单
List<MenuEntity> menuList = menuDao.getMenuListByRole(roleId);
//找到所有的1级菜单
List<MenuEntity> mList = new ArrayList<>();
for (int i = 0; i < menuList.size(); i++) {
if (menuList.get(i).getParentId()==0){
mList.add(menuList.get(i));
}
}
//为一级菜单设置子菜单准备递归
for (MenuEntity menu:mList) {
//获取父菜单下所有子菜单调用getChildList
List<MenuEntity> childList = getChildList(String.valueOf(menu.getMenuId()),menuList);
menu.setChildList(childList);
}
return mList;
}
public List<MenuEntity> getChildList(String id,List<MenuEntity> menuList){
//构建子菜单
List<MenuEntity> childList = new ArrayList<>();
//遍历传入的list
for (MenuEntity menu:menuList) {
//所有菜单的父id与传入的根节点id比较,若相等则为该级菜单的子菜单
if (String.valueOf(menu.getParentId()).equals(id)){
childList.add(menu);
}
}
//递归
for (MenuEntity m:childList) {
m.setChildList(getChildList(String.valueOf(m.getMenuId()),menuList));
}
if (childList.size() == 0){
return null;
}
return childList;
}
原文链接:https://blog.csdn.net/GayFei/article/details/81262904