1.在DAO中的实现代码:
public List<TreeResult> parseMenuTree(List<TreeResult> list){ List<TreeResult> result = new ArrayList<>(); //1.获取第一个节点 for (TreeResult menu:list) { if(null == menu.getParentId()){ result.add(menu); } } //2.获取递归子节点 for (TreeResult parent:result) { parent = menuChild(parent,list); } return result; } public TreeResult menuChild(TreeResult parent,List<TreeResult> list){ for (TreeResult menu:list) { if(Objects.equals(parent.getId(),menu.getParentId())){ parent.getChildren().add(menu); menu = menuChild(menu,list); } } return parent; } |
2.在Controller中的实现代码:
@ApiOperation(value = "动态菜单", httpMethod = "POST", produces = "application/json;charset=UTF-8") @ApiImplicitParam(value = "token", name = "token", dataType = "String", paramType = "header") @PostMapping("/api/menu/tree") public Result menuTree(HttpServletRequest request) { Map<String, Object> map = new HashMap<>(); try { User user = userService.getDao().findById(Integer.valueOf(tokenService.valid(request.getHeader("token")))); if (user == null) { return Result.fail(902, "用户登录失效,请重新登录"); } if (Enums.UserType.Driver == user.getType()) { return Result.fail(903, "该用户没有权限"); } if (Enums.UserType.Passenger == user.getType()) { return Result.fail(903, "该用户没有权限"); } //根据用户对应的角色获取角色对应的菜单id List<Integer> integers = roleAndMenuService.getDao().findByRoleId(user.getRoles()); List<String> list = integers.stream().map(x -> x + "").collect(Collectors.toList()); String menus = String.join(",", list); //根据菜单id获取对应的菜单 List<TreeResult> tree = menuService.getDao().findTree(menus); //将菜单列表转成树结构 List<TreeResult> treeResults = menuService.getDao().parseMenuTree(tree); map.put("list", treeResults); return Result.ok(map); } catch (Exception e) { e.printStackTrace(); return Result.fail(901, e.getMessage()); } } |
3.TreeResult实体类:
@Getter @Setter public class TreeResult { private Integer id; private String icon; private String menuName; private String menuType; private String menuUrl; private Integer parentId; private List<TreeResult> children = new ArrayList<TreeResult>(); } |