/** * 查询所有菜单 * @return */ @Override public BaseWebResponse<Object> getAllMenus() { List<SystemMenuInfo> systemMenuInfoList = menuInfoMapper.getAllMenus(); List<SystemMenuInfo> menuTree = buildMenuTree(systemMenuInfoList); System.out.println("menuTree: "+menuTree); return setResultSuccess("信息查询成功", menuTree); } /** * 构建菜单树 * @param allMenus * @return */ private List<SystemMenuInfo> buildMenuTree(List<SystemMenuInfo> allMenus) { //用于存放根菜单 List<SystemMenuInfo> rootMenus = new ArrayList<>(); Map<Integer, List<SystemMenuInfo>> menuMap = new HashMap<>(); // 将菜单按照父菜单ID分组,放在menuMap中 for (SystemMenuInfo menu : allMenus) { int parentId = menu.getPid() != null ? menu.getPid() : 0; if (!menuMap.containsKey(parentId)) { menuMap.put(parentId, new ArrayList<>()); } menuMap.get(parentId).add(menu); } // 从根菜单开始,构建菜单树 rootMenus.addAll(menuMap.getOrDefault(0, new ArrayList<>())); System.out.println("rootMenus: "+rootMenus); for (SystemMenuInfo rootMenu : rootMenus) { buildSubMenuTree(rootMenu, menuMap); } return rootMenus; } /** * 根据父菜单节点逐级构建子树,按顺序排列 * @param parentMenu * @param menuMap */ private void buildSubMenuTree(SystemMenuInfo parentMenu, Map<Integer, List<SystemMenuInfo>> menuMap) { //获取根菜单的子节点列表 List<SystemMenuInfo> children = menuMap.getOrDefault(parentMenu.getMenuId(), new ArrayList<>()); Collections.sort(children); parentMenu.setChildren(children); for (SystemMenuInfo childMenu : children) { buildSubMenuTree(childMenu, menuMap); } }
/** * 找出给定子菜单的所有父菜单并添加到 menuInfoList 中 * @param subMenu * @param menuInfoList */ public void addParentMenusToMenuInfoList(SystemMenuInfo subMenu, List<SystemMenuInfo> menuInfoList) { if (subMenu == null || subMenu.getPid() == null) { return; } // 获取系统内所有菜单 List<SystemMenuInfo> allMenus = menuInfoMapper.getAllMenus(); //存放所有菜单,用于查找父菜单 Map<Integer, SystemMenuInfo> map = new HashMap<>(); for(int i=0;i<allMenus.size();i++){ SystemMenuInfo menu = allMenus.get(i); map.put(menu.getMenuId(), menu); } // 递归查找父菜单并添加到 menuInfoList 中 addParentMenusRecursively(map, subMenu, menuInfoList); } /** * 递归地查找父菜单并添加到 menuInfoList中 */ private void addParentMenusRecursively(Map<Integer, SystemMenuInfo> map, SystemMenuInfo menu, List<SystemMenuInfo> menuInfoList) { if (menu.getPid() == 0) { // 如果父菜单的 pid 为 0,说明已经到达根菜单,递归结束 return; } //根据当前菜单的 pid 查找父菜单 SystemMenuInfo parentMenu = findParentMenu(map, menu.getPid()); if (parentMenu != null) { // 如果父菜单存在且没有被添加过,就添加到 menuInfoList 中 if (!menuInfoList.contains(parentMenu)) { menuInfoList.add(parentMenu); } // 继续递归查找当前父菜单的父菜单 addParentMenusRecursively(map, parentMenu, menuInfoList); } } /** * 根据 pid 查找父菜单 */ private SystemMenuInfo findParentMenu(Map<Integer, SystemMenuInfo> map, Integer parentId) { if(map.containsKey(parentId)) { return map.get(parentId); } return null; }
文章来源地址https://www.toymoban.com/news/detail-629402.html
文章来源:https://www.toymoban.com/news/detail-629402.html
到了这里,关于java实现多级菜单的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!