1. 获取用户信息并
从用户session 中获取用户信息
@Operation(summary = "查询当前用户菜单")
@GetMapping("/getSelfMenu")
public Result<List<RouterVO>> getSelfMenu() {
UserInfo userLoginInfo = (UserInfo) StpUtil.getSession().get("userInfo");
Long id = userLoginInfo.getId();
return Result.success(menuService.getMenuByUserId(id));
}
2. 查询用户菜单并递归构建
/**
* 根据用户id 获取菜单
* @param id
* @return
*/
@Override
public List<RouterVO> getMenuByUserId(Long id) {
List<SysMenu> menus = menuMapper.getMenuListByUserId(id);
//通过递归设置菜单的树形结构
// 1、获取所有的1级菜单【parentId=0】
// 2、遍历1级菜单,获取他所有的子元素【其他数据的parentId=当前元素的id】
List<RouterVO> router = getRourerList(menus);
return router;
}
/**
* 获取路由
* @param menus
* @return
*/
private List<RouterVO> getRourerList(List<SysMenu> menus) {
List<RouterVO> routerVOS = new ArrayList<>();
// 获取所有一级路由
List<SysMenu> parentMenu = menus.stream().filter(item -> item.getParentId() == 0).collect(Collectors.toList());
// 转换类型对象
for (SysMenu menu: parentMenu) {
RouterVO routerVO = new RouterVO();
BeanUtil.copyProperties(menu, routerVO);
routerVOS.add(routerVO);
}
// 循环1级路由, 获取子菜单
for (RouterVO routerVO: routerVOS) {
// 获取所有子节点
List<RouterVO> childList = buildTree(menus, routerVO.getId());
routerVO.setChildren(childList);
}
return routerVOS;
}
/**
* 递归匹配所有的子节点
* @param menus
* @param parentId
* @return
*/
private List<RouterVO> buildTree(List<SysMenu> menus, Long parentId) {
List<RouterVO> childList = new ArrayList<>();
for (SysMenu menu: menus) {
// 判断menu parentId 是否等于传入parentId
if (menu.getParentId().equals(parentId)) {
RouterVO routerVO = new RouterVO();
BeanUtil.copyProperties(menu, routerVO);
childList.add(routerVO);
}
}
// 递归childList 可能还存在的子节点
for (RouterVO childItem: childList) {
childItem.setChildren(buildTree(menus, childItem.getId()));
}
return childList;
}
3. 连表查询用户菜单
public interface SysMenuMapper extends BaseMapper<SysMenu> {
@Select("select m.* from sys_user_role ur JOIN sys_role r ON ur.role_id = r.id " +
"JOIN sys_role_menu rm ON r.id = rm.role_id JOIN sys_menu m ON rm.menu_id = m.id WHERE m.deleted = 0 " +
"AND m.status = 0 AND ur.user_id = #{id} ORDER BY sort ASC;")
List<SysMenu> getMenuListByUserId(@Param("id") Long id);
}
测试: