菜单递归

浪子不回头ぞ 提交于 2020-01-01 15:55:00
/** * @ClassName: FunctionService * @Description: 功能菜单 * @author: yaozhenhua * @date: 2018/12/26 12:29 */@Servicepublic class MenuService {        @Resource    MenuDao menuDao;        /**     *查询可用且上线的菜单     *     * @param     * @author: yaozhenhua  2019/3/27 17:24     */    public List<MenuVO> listMenu() throws InstantiationException, IllegalAccessException, AobpException {        //结果处理容器        List<MenuVO> menuVOS = new ArrayList<>();        //查询一级菜单        List<MenuBO> menuBOS = menuDao.listParentMenu();        if(!EmptyUtils.isEmpty(menuBOS)){            //一级菜单排序            Collections.sort(menuBOS, new Comparator<MenuBO>() {                @Override                public int compare(MenuBO o1, MenuBO o2) {                    int ret = 0;                    ret = o1.getParentSequence().compareTo(o2.getParentSequence());                    return ret;                }            });                            menuVOS = BeanCopyUtils.copyList(menuBOS,MenuVO.class);                      for(int i=0; i<menuBOS.size(); i++){                MenuBO menuBO = menuBOS.get(i);                MenuVO menuVO = menuVOS.get(i);                //查询子菜单并排序                List<MenuVO> subMenuVOS = listSubMenu(menuBO.getId(),1);                menuVO.setSubs(subMenuVOS);                }            }                return menuVOS;    }        /**     *根据父id查询子菜单     *     * @param parentId     * @author: yaozhenhua  2019/3/27 17:24     */    public List<MenuVO> listSubMenu(Long parentId, int alarm) throws InstantiationException, IllegalAccessException, AobpException {         //计数器 递归20次抛出异常,菜单层级最大没有超过20层的。     if(alarm>20){            throw new AobpException(ExceptionConstant.INTERNAL_ERR,"递归次数超过20次异常");        }        //查询出此父菜单下的子菜单        List<MenuBO>  menuBOS= menuDao.listMenuByParentId(parentId);        //结果容器        List<MenuVO> menuVOS = new ArrayList<>();        //查看子菜单是不是还有下一级菜单(判定条件  用id作为父id去查 )        if (!EmptyUtils.isEmpty(menuBOS)){            Collections.sort(menuBOS, new Comparator<MenuBO>() {                @Override                public int compare(MenuBO o1, MenuBO o2) {                    int ret = 0;                    ret = o1.getChildSequence().compareTo(o2.getChildSequence());                    return ret;                }            });                menuVOS = BeanCopyUtils.copyList(menuBOS,MenuVO.class);                for (int i = 0; i < menuBOS.size(); i++) {                MenuBO menuBO = menuBOS.get(i);                MenuVO menuVO = menuVOS.get(i);                List<MenuVO> nextMenuVOS = listSubMenu(menuBO.getId(),alarm+1);                if(!EmptyUtils.isEmpty(nextMenuVOS)){                        menuVO.setSubs(nextMenuVOS);                }            }                               }        return menuVOS;    }}另一种方式:
/** * @ClassName: MenuService * @author: yaozhenhua * @date: 2019/3/27 15:59 */public class MenuService {        @Transactional(readOnly = true)    public List<Menu> selectDocMenuList() {        // 查询全部文档        List<Menu> rootMenuList = docDao.selectListExpUnable();        // 最终的菜单        List<Menu> docList = new ArrayList<Menu>();        // 没有父ID的文档, 作为一级菜单        for (Menu rootMenu : rootMenuList) {            if (rootMenu.getDocPid() == null) {                docList.add(rootMenu);            }        }                // 为一级菜单添加子菜单        for (Menu menu : docList) {            menu.setChildList(getChild(menu.getDocId(), rootMenuList));        }        if (docList != null && docList.size() > 0) {            // 为list排序            this.mySort(docList, "docOrder", null);        }                return docList;    }        private List<Menu> getChild(String docId, List<Menu> rootMenu) {        if (StringUtils.isBlank(docId)) {            throw new BusinessException("文档id不能为空");        }        // 子菜单        List<Menu> childList = new ArrayList<>();        for (Menu menu : rootMenu) {            // 遍历所有节点,将父菜单id与传过来的type比较            if (menu.getDocPid() != null) {                if (menu.getDocPid().equals(docId)) {                    childList.add(menu);                }            }        }        // 把子菜单的子菜单再循环一遍        for (Menu menu : childList) {// 没有内容的子菜单还有子菜单            try {                if (menu.getDocContentHref() != null) {                    menu.setDocContent(new String(menu.getDocContentHref(), "UTF-8"));                }                if (StringUtils.isBlank(menu.getDocContent())) {                    // 递归                    menu.setChildList(getChild(menu.getDocId(), rootMenu));                }            } catch (UnsupportedEncodingException e) {                e.printStackTrace();            }        } // 递归退出条件        if (childList != null && childList.size() > 0) {            this.mySort(childList, "docOrder", null);        } else {            return null;        }                return childList;    }}
public class Menu {
  // 菜单id
  private String id;
  // 菜单名称
  private String name;
  // 父菜单id
  private String parentId;
  // 菜单url
  private String url;
  // 菜单图标
  private String icon;
  // 菜单顺序
  private int order;
  // 子菜单
  private List<Menu> children;
  // ... 省去getter和setter方法以及toString方法
}

菜单一般需要排序,我们根据Menu的order字段进行排序:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/*
  * 排序,根据order排序
  */
 public Comparator<Menu> order(){
   Comparator<Menu> comparator = new Comparator<Menu>() {
     @Override
     public int compare(Menu o1, Menu o2) {
       if(o1.getOrder() != o2.getOrder()){
         return o1.getOrder() - o2.getOrder();
       }
       return 0;
     }
   };
   return comparator;
 }

生成树的方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public Map<String,Object> findTree(){
  Map<String,Object> data = new HashMap<String,Object>();
    try {//查询所有菜单
      List<Menu> allMenu = menuDao.findTree();
      //根节点
      List<Menu> rootMenu = new ArrayList<Menu>();
      for (Menu nav : allMenu) {
        if(nav.getParentId().equals("0")){//父节点是0的,为根节点。
          rootMenu.add(nav);
        }
      }
      /* 根据Menu类的order排序 */
      Collections.sort(rootMenu, order());
      //为根菜单设置子菜单,getClild是递归调用的
      for (Menu nav : rootMenu) {
        /* 获取根节点下的所有子节点 使用getChild方法*/
        List<Menu> childList = getChild(nav.getId(), allMenu);
        nav.setChildren(childList);//给根节点设置子节点
      }
      /**
       * 输出构建好的菜单数据。
       *
       */
      data.put("success""true");
      data.put("list", rootMenu);
      return data;
    catch (Exception e) {
      data.put("success""false");
      data.put("list"new ArrayList());
      return data;
    }
  }

获取子菜单:

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
   * 获取子节点
   * @param id 父节点id
   * @param allMenu 所有菜单列表
   * @return 每个根节点下,所有子菜单列表
   */
  public List<Menu> getChild(String id,List<Menu> allMenu){
    //子菜单
    List<Menu> childList = new ArrayList<Menu>();
    for (Menu nav : allMenu) {
      // 遍历所有节点,将所有菜单的父id与传过来的根节点的id比较
      //相等说明:为该根节点的子节点。
      if(nav.ParentId().equals(id)){
        childList.add(nav);
      }
    }
    //递归
    for (Menu nav : childList) {
      nav.setChildren(getChild(nav.getId(), allMenu));
    }
    Collections.sort(childList,order());//排序
    //如果节点下没有子节点,返回一个空List(递归退出)
    if(childList.size() == 0){
      return new ArrayList<Menu>();
    }
    return childList;
  }

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!