核心思想有两点:
1 实体类的设计,除了基本的属性,还要有子菜单List,如下图
2 就是递归方法的核心思想:
①:获取到所有的菜单列表(当然如果是当前用户下的)
②:编写递归方法:方法参数两个(1是所有的菜单列表,2是顶级菜单的parentId)
循环所有菜单列表,判断当前菜单parentId等于传入的parentId,就将此菜单的id当做parentId和所有菜单列表再调用递归,同时将递归的结果存到顶级菜单的childMenus中去,这样既能实现无论有多少级子菜单都能构建成树状,如下图
下面贴上源码:
public interface SysMenuMapper extends Mapper {
/**
* 获取菜单列表
* @return
*/
List
//内部方法-递归构建菜单树
private List
@Test
void menuTreeTest2() {
//所有菜单
List rootMenu = this.menuMapper.getMenuList();
List resultMenuList = buildMenuTree(rootMenu, 0);
System.out.println(resultMenuList);
}
以下是效果:
[
Menu(id=1,
name=资源管理,
parentId=0,
type=0,
permission=resource,
url=resource,
order=1,
childMenus=[
Menu(id=4,
name=资源添加,
parentId=1,
type=1,
permission=resource:insert,
url=resource,
order=1,
childMenus=[
]),
Menu(id=5,
name=资源修改,
parentId=1,
type=1,
permission=resource:update,
url=resource,
order=1,
childMenus=[
]),
Menu(id=6,
name=资源删除,
parentId=1,
type=1,
permission=resource:del,
url=resource,
order=1,
childMenus=[
]),
Menu(id=7,
name=资源查看,
parentId=1,
type=1,
permission=resource:select,
url=resource,
order=1,
childMenus=[
])]),
Menu(id=2,
name=运营管理,
parentId=0,
type=0,
permission=operation,
url=operation,
order=1,
childMenus=[
Menu(id=8,
name=审核管理,
parentId=2,
type=0,
permission=operation:audit,
url=operation,
order=1,
childMenus=[
Menu(id=10,
name=实名审核,
parentId=8,
type=1,
permission=operation:audit:certification,
url=operation,
order=1,
childMenus=[
]),
Menu(id=11,
name=资源审核,
parentId=8,
type=1,
permission=operation:audit:resource,
url=operation,
order=1,
childMenus=[
])]),
Menu(id=9,
name=发布管理,
parentId=2,
type=0,
permission=operation:publish,
url=operation,
order=1,
childMenus=[
])]),
Menu(id=3,
name=数据管理,
parentId=0,
type=0,
permission=data,
url=data,
order=1,
childMenus=[
])]