菜单树形显示

菜单树形显示的三种方式

1.for()递归,入口一级分类,递归终止条件(父菜单id = 子菜单的父id)常用
2.map stream流
3.sql 的 递归函数

步骤

1.查询出所有菜单 menuList
	public List<Category> treeList() {
   		//查询出所有分类
    	List<Category> categoryList = categoryMapper.getCategoryList();

    	//将所有分类,按照要求封装后返回
   		List<Category> categoryTree = buildTree(categoryList);
    	return categoryTree;
	}
2.封装menuList 返回treeList-->返回前端
	private List<Category> buildTree(List<Category> categoryList){
        //创建用于封装最后数据的list集合
        List<Category> categoryTree = new ArrayList<>();

        //遍历categoryList ,找出一级分类
        for (Category category : categoryList) {
            if(category.getParentCid().equals(new Long(0))){
                categoryTree.add(setChildren(category,categoryList));
        	}
       	}
        return categoryTree;
	}
3.向父菜单封装子菜单列表
	private Category setChildren(Category oneCategory,List<Category> categoryList){
        //1 因为向一层菜单里面放二层菜单,二层里面还要放三层,把对象初始化
        oneCategory.setCategoryList(new ArrayList<Category>());

        //遍历categoryList找出一级分类的子分类
        for (Category category : categoryList) {
            if(oneCategory.getCatId().equals(category.getParentCid())){
                oneCategory.getCategoryList().add(setChildren(category,categoryList));
            }
        }
        return oneCategory;
}

4.三个方法的注意点:
	1.menuList从第一个函数一直往下传,只用这一个
	2.递归封装子菜单的入口是 一级菜单
	3.setChildren(Menu m,List<MenuList>)中,开始得将menu 的 子菜单menuList赋初始值,因为后面得调用menu.getMenuList().add(),避免null指针异常

おすすめ

転載: blog.csdn.net/Chen4852010/article/details/120644566