package com.example.core.xk.service.impl;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSONObject;
import com.example.core.xk.dao.SysMenuMapper;
import com.example.core.xk.service.MenuService;
@Service
public class MenuServiceImpl implements MenuService {
@Autowired
private SysMenuMapper SysMenuMapper;
@Override
public List<JSONObject> getMenu(Integer roleId) {
// 原始的数据
List<JSONObject> allMenu;
if (roleId == 1) {
allMenu = SysMenuMapper.getAllMenu();
} else {
allMenu = SysMenuMapper.getAllMenuByRoleId(roleId);
}
// 最后的结果
List<JSONObject> menuList = new ArrayList<JSONObject>();
for (JSONObject jsonObject : allMenu) {
if (jsonObject.getInteger("parentId").equals(0)) {
menuList.add(jsonObject);
}
}
// 为一级菜单设置子菜单,getChild是递归调用的
for (JSONObject jsonObject : menuList) {
jsonObject.put("children", getChild(jsonObject.getInteger("menuId"), allMenu));
}
return menuList;
}
private List<JSONObject> getChild(Integer menuId, List<JSONObject> allMenu) {
// 子菜单
List<JSONObject> childList = new ArrayList<>();
for (JSONObject jsonObject : allMenu) {
// 遍历所有节点,将父菜单id与传过来的id比较
if (!jsonObject.getInteger("parentId").equals(0)) {
if (jsonObject.getInteger("parentId").equals(menuId)) {
childList.add(jsonObject);
}
}
}
// 递归终止的条件,没有子权限时
if (childList.size() == 0) {
return null;
}
// 如果有子菜单还有子菜单,把子菜单的子菜单再循环一遍
for (JSONObject jsonObject : childList) {
jsonObject.put("children", getChild(jsonObject.getInteger("menuId"), allMenu));
}
return childList;
}
}
无限级菜单遍历
最新推荐文章于 2023-03-02 22:55:59 发布