尚筹网:菜单维护之在页面显示树形结构的后端部分

把树形结构组装好,具体来说是:给前端返回根节点对象。在根节点中包含子节点,子节点中再包含下一级的子节点。
在这里插入图片描述

代码

handler方法中的具体操作

/atcrowdfunding-admin-2-component/src/main/java/com/atguigu/crowd/funding/handler/MenuHandler.java

@RequestMapping("/menu/get/whole/tree")
public ResultEntity<Menu> getWholeTree() {
	
	// 1.查询所有的树形节点用于组装
	List<Menu> menuList = menuService.getAll();
	
	// 2.将List<Menu>转换为Map<Menu的id,Menu>
	Map<Integer,Menu> menuMap = new HashMap<>();
	
	for (Menu menu : menuList) {
		Integer id = menu.getId();
		menuMap.put(id, menu);
	}
	
	// 3.声明变量用于存储根节点对象
	Menu rootNode = null;
	
	// 4.遍历List<Menu>
	for (Menu menu : menuList) {
		
		// 5.获取当前Menu对象的pid属性
		Integer pid = menu.getPid();
		
		// 6.判断pid是否为null
		if(pid == null) {
			
			// 7.如果pid为null,说明当前节点是根节点,所以赋值
			rootNode = menu;
			
			// 8.根节点没有父节点,所以不必找父节点组装,本次for循环停止执行,继续执行下一次循环
			continue ;
		}
		
		// 9.既然pid不为null,那么我们根据这个pid查找当前节点的父节点。
		Menu father = menuMap.get(pid);
		
		// 10.组装:将menu添加到maybeFather的子节点集合中
		father.getChildren().add(menu);
	}
	
	return ResultEntity.successWithData(rootNode);
}

备注:尽量不要在代码中出现 嵌套for(N*N), 可以将两个for拆开成先后执行(N+N)

service方法

/atcrowdfunding-admin-2-component/src/main/java/com/atguigu/crowd/funding/service/impl/MenuServiceImpl.java

@Service
public class MenuServiceImpl implements MenuService {

	@Autowired
	private MenuMapper menuMapper;
	
	@Override
	public List<Menu> getAll() {
		// TODO Auto-generated method stub
		return menuMapper.selectByExample(new MenuExample());
	}

}

测试

http://localhost:8080/atcrowdfunding-admin-1-webui/menu/get/whole/tree.json

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值