权限菜单封装成树结构


    private Map testQueryMenuList(List<Menu> rootMenu) {
        // 查看结果
        for (Menu menu : rootMenu) {
            System.out.println(menu);
        }
        // 最后的结果
        List<Menu> menuList = new ArrayList<Menu>();
        // 先找到所有的一级菜单
        for (Menu value : rootMenu) {
            // 一级菜单没有parentId
            if (!StringUtils.isEmpty(value.getParentId())) {
                menuList.add(value);
            }
        }
        // 为一级菜单设置子菜单,getChild是递归调用的
        for (Menu menu : menuList) {
            menu.setChildMenus(getChild(menu.getId(), rootMenu));
        }
        Map<String, Object> jsonMap = new HashMap<>();
        jsonMap.put("menu", menuList);
        System.out.println(JSON.toJSONString(jsonMap));
        return jsonMap;
    }


    private List<Menu> getChild(Long id, List<Menu> rootMenu) {
        // 子菜单
        List<Menu> childList = new ArrayList<>();
        for (Menu menu : rootMenu) {
            // 遍历所有节点,将父菜单id与传过来的id比较
            if (!StringUtils.isEmpty(menu.getParentId())) {
                if (menu.getParentId().equals(id)) {
                    childList.add(menu);
                }
            }
        }
        // 把子菜单的子菜单再循环一遍
        for (Menu menu : childList) {
            // 没有url子菜单还有子菜单
            if (!StringUtils.isEmpty(menu.getPath())) {
                // 递归
                menu.setChildMenus(getChild(menu.getId(), rootMenu));
            }
        }
        // 递归退出条件
        if (childList.size() == 0) {
            return null;
        }
        return childList;
    }

个人->岗位->角色->菜单,查出数据

发布了66 篇原创文章 · 获赞 85 · 访问量 14万+

猜你喜欢

转载自blog.csdn.net/qq_38380025/article/details/97386659
今日推荐