在层级查询菜单时意见有所分歧,想法有两种一种是动态查询,但是会增加服务器的压力,另一种方法是全部返回的数据,由前端去控制展示效果。
层级查询树状菜单,想到使用递归去做遍历查询,在此记录一下
实体类和到层就不再生成代码,核心代码是service层的逻辑处理主要包括两部分内容
//层级获取菜单
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;
}
service主要逻辑实现如上所示,除了递归暂时没有更好的思路,若有会继续补充。
返回的数据格式如下
"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
}
]
}