Skip to content
Permalink
Branch: master
Find file Copy path
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
104 lines (89 sloc) 2.31 KB

多级菜单递归遍历成树

实现

@Override
public Map<String, Object> getPageResourceTree() {
    Map<String,Object> map=new HashMap<>();

    //获取全部page
    List<SysResourcePage> sysResourcePages = sysResourcePageMapper.selectAlls();
    //递归输出outpage(页面菜单)
    List<SysResourcePage> outPageList=new ArrayList<>();
    //一级菜单 0 null
    for (int i=0;i<sysResourcePages.size();i++){
        if (null==(sysResourcePages.get(i).getParentId()) || (0==(sysResourcePages.get(i).getParentId()))){
            outPageList.add(sysResourcePages.get(i));
        }
    }
    //为一级菜单设置子菜单
    for (SysResourcePage outPage:outPageList){
        outPage.setChildMenus(getChild(outPage.getId(),sysResourcePages));
    }
    map.put("pageList",outPageList);
    return map;
}

//递归调用
private List<SysResourcePage> getChild(Integer id,List<SysResourcePage> sysResourcePages){
    //子菜单
    List<SysResourcePage> childList=new ArrayList<>();
    for (SysResourcePage page:sysResourcePages){
        //遍历所有节点,将父菜单id与传过来的id比较
        if (null != page.getParentId()){
            if (page.getParentId()==id){
                childList.add(page);
            }
        }
    }
    //把子菜单的子菜单再循环一遍
    for (SysResourcePage page:childList){
       // if (StrUtil.hasBlank(page.getUrl())){
            //递归
            page.setChildMenus(getChild(page.getId(),sysResourcePages));
        //}
    }
    // 递归退出条件
    if (childList.size()==0){
        return null;
    }
    return childList;
}

实体类

public class SysResourcePage {

    /**
     * 编号,主键,资源page表
     */
    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;

    /**
     * 资源名称
     */
    private String name;

    /**
     * 权限访问路径
     */
    private String url;

    /**
     * 父编号
     */
    private Integer parentId;

    /**
     * 资源类型:0目录 1菜单 2按钮
     */
    private Integer type;

    /**
     * 显示顺序
     */
    private Integer priority;

    /**
     * 图标
     */
    private String icon;

    /**
     * 是否可用:1有效2删除
     */
    private Integer status;

    @Transient
    private List<SysResourcePage> childMenus;
}
You can’t perform that action at this time.