一、获取全部菜单

image.png

1、controller

  1. //获取全部菜单
  2. @ApiOperation(value = "查询所有菜单")
  3. @GetMapping
  4. public R indexAllPermission() {
  5. List<Permission> list = permissionService.queryAllMenuGuli();
  6. return R.ok().data("children",list);
  7. }

2、serviceImpl

  1. //获取全部菜单
  2. @Override
  3. public List<Permission> queryAllMenuGuli() {
  4. //1 查询菜单表所有数据
  5. LambdaQueryWrapper<Permission> wrapper = new LambdaQueryWrapper<>();
  6. wrapper.orderByDesc(Permission::getId);
  7. List<Permission> permissionList = baseMapper.selectList(wrapper);
  8. //2 把查询所有菜单list集合按照要求进行封装
  9. List<Permission> resultList = bulidPermission(permissionList);
  10. return resultList;
  11. }
  12. // 找到递归调用的起始节点:即顶层菜单
  13. //把返回所有菜单list集合进行封装的方法
  14. public static List<Permission> bulidPermission(List<Permission> permissionList) {
  15. //创建list集合,用于数据最终封装
  16. List<Permission> finalNode = new ArrayList<>();
  17. //把所有菜单list集合遍历,得到顶层菜单 pid=0菜单,设置level是1
  18. permissionList.forEach(e -> {
  19. //得到顶层菜单 pid=0菜单
  20. if("0".equals(e.getPid())){
  21. //设置顶层菜单的level是1
  22. e.setLevel(1);
  23. //根据顶层菜单,向里面进行查询子菜单,封装到finalNode里面
  24. finalNode.add(selectChildren(e,permissionList));
  25. }
  26. });
  27. return finalNode;
  28. }
  29. /**
  30. *
  31. * @param permissionNode 父菜单
  32. * @param permissionList 所有的菜单
  33. * @return
  34. */
  35. private static Permission selectChildren(Permission permissionNode, List<Permission> permissionList) {
  36. //1 因为向一层菜单里面放二层菜单,二层里面还要放三层,把子菜单对象初始化
  37. permissionNode.setChildren(new ArrayList<Permission>());
  38. //2 遍历所有菜单list集合,进行判断比较,比较父菜单id和子菜单pid值是否相同
  39. permissionList.forEach(permission -> {
  40. //判断父菜单id和子菜单pid值是否相同
  41. if(permission.getPid().equals(permissionNode.getId())){
  42. //把父菜单的level值+1,赋值给子菜单
  43. int level = permissionNode.getLevel() + 1;
  44. permission.setLevel(level);
  45. //如果children为空,进行初始化操作
  46. if(permission.getChildren() == null){
  47. permission.setChildren(new ArrayList<Permission>());
  48. }
  49. //把查询出来的子菜单放到父菜单里面
  50. permissionNode.getChildren().add(selectChildren(permission,permissionList));
  51. // permissionNode.setChildren(new ArrayList<Permission>(){
  52. // {
  53. // add(selectChildren(permission,permissionList));
  54. // }
  55. // });
  56. }
  57. });
  58. return permissionNode;
  59. }

二、递归删除菜单

1、controller

  1. @ApiOperation(value = "递归删除菜单")
  2. @DeleteMapping("remove/{id}")
  3. public R remove(@PathVariable String id) {
  4. permissionService.removeChildByIdGuli(id);
  5. return R.ok();
  6. }

2、serviceImpl

  1. @Override
  2. public void removeChildByIdGuli(String id) {
  3. //1 创建list集合,用于封装所有删除菜单id值
  4. List<String> idList = new ArrayList<>();
  5. //2 向idList集合设置删除菜单id
  6. this.selectPermissionChildById(id,idList);
  7. //把当前id封装到list里面
  8. idList.add(id);
  9. //执行删除操作
  10. baseMapper.deleteBatchIds(idList);
  11. }
  12. //2 根据当前菜单id,查询菜单里面子菜单id,封装到list集合
  13. private void selectPermissionChildById(String id, List<String> idList) {
  14. //查询菜单里面子菜单id
  15. LambdaQueryWrapper<Permission> wrapper = new LambdaQueryWrapper<>();
  16. wrapper.eq(Permission::getPid,id);
  17. List<Permission> childIdList = baseMapper.selectList(wrapper);
  18. if(!CollectionUtils.isEmpty(childIdList)){
  19. //把childIdList里面菜单id值获取出来,封装idList里面,做递归查询
  20. childIdList.stream().forEach(item -> {
  21. //封装idList里面
  22. idList.add(item.getId());
  23. //递归查询
  24. this.selectPermissionChildById(item.getId(), idList);
  25. });
  26. }
  27. }

三、给角色分配菜单

1、controller

  1. @ApiOperation(value = "给角色分配菜单")
  2. @PostMapping("/doAssign")
  3. public R doAssign(String roleId,String[] permissionId) {
  4. permissionService.saveRolePermissionRealtionShipGuli(roleId,permissionId);
  5. return R.ok();
  6. }

2、serviceImpl

  1. @Override
  2. public void saveRolePermissionRealtionShipGuli(String roleId, String[] permissionIds) {
  3. //roleId角色id
  4. //permissionId菜单id 数组形式
  5. // 删除已分配的菜单
  6. LambdaQueryWrapper<RolePermission> wrapper = new LambdaQueryWrapper<>();
  7. wrapper.eq(RolePermission::getRoleId,roleId);
  8. rolePermissionService.remove(wrapper);
  9. // 创建list集合,用于封装添加数据
  10. List<RolePermission> rolePermissionList = new ArrayList<>();
  11. //遍历所有菜单数组
  12. for(String perId : permissionIds) {
  13. //RolePermission对象
  14. RolePermission rolePermission = new RolePermission();
  15. rolePermission.setRoleId(roleId);
  16. rolePermission.setPermissionId(perId);
  17. //封装到list集合
  18. rolePermissionList.add(rolePermission);
  19. }
  20. //添加到角色菜单关系表
  21. rolePermissionService.saveBatch(rolePermissionList);
  22. }

四、根据角色获取菜单

1、controller

  1. @ApiOperation(value = "根据角色获取菜单")
  2. @GetMapping("toAssign/{roleId}")
  3. public R toAssign(@PathVariable String roleId) {
  4. List<Permission> list = permissionService.selectAllMenu(roleId);
  5. return R.ok().data("children", list);
  6. }

2、serviceImpl

  1. //根据角色获取菜单
  2. @Override
  3. public List<Permission> selectAllMenu(String roleId) {
  4. //获取所有菜单
  5. // CAST(id AS SIGNED),将id转换成int类型
  6. // List<Permission> allPermissionList = baseMapper.selectList(new QueryWrapper<Permission>().orderByAsc("CAST(id AS SIGNED)"));
  7. LambdaQueryWrapper<Permission> wrapper = new LambdaQueryWrapper<>();
  8. wrapper.orderByDesc(Permission::getId);
  9. List<Permission> allPermissionList = baseMapper.selectList(wrapper);
  10. // 根据角色id获取角色权限
  11. // List<RolePermission> rolePermissionList = rolePermissionService.list(new QueryWrapper<RolePermission>().eq("role_id",roleId));
  12. LambdaQueryWrapper<RolePermission> wrapper1 = new LambdaQueryWrapper<>();
  13. wrapper1.eq(RolePermission::getRoleId,roleId);
  14. List<RolePermission> rolePermissionList = rolePermissionService.list(wrapper1);
  15. // 获取角色对应的权限id
  16. List<String> permissionIdList = rolePermissionList.stream().map(RolePermission::getPermissionId).collect(Collectors.toList());
  17. // 设置权限列表的select字段
  18. allPermissionList.forEach(p -> {
  19. if(permissionIdList.contains(p.getId())){
  20. p.setSelect(true);
  21. }else {
  22. p.setSelect(false);
  23. }
  24. });
  25. //转换给角色id与角色权限对应Map对象
  26. // List<String> permissionIdList = rolePermissionList.stream().map(e -> e.getPermissionId()).collect(Collectors.toList());
  27. // allPermissionList.forEach(permission -> {
  28. // if(permissionIdList.contains(permission.getId())) {
  29. // permission.setSelect(true);
  30. // } else {
  31. // permission.setSelect(false);
  32. // }
  33. // });
  34. // for (int i = 0; i < allPermissionList.size(); i++) {
  35. // Permission permission = allPermissionList.get(i);
  36. // for (int m = 0; m < rolePermissionList.size(); m++) {
  37. // RolePermission rolePermission = rolePermissionList.get(m);
  38. // if(rolePermission.getPermissionId().equals(permission.getId())) {
  39. // permission.setSelect(true);
  40. // }
  41. // }
  42. // }
  43. List<Permission> permissionList = bulid(allPermissionList);
  44. return permissionList;
  45. }
  46. /**
  47. * 使用递归方法建菜单
  48. * @param treeNodes
  49. * @return
  50. */
  51. private static List<Permission> bulid(List<Permission> treeNodes) {
  52. List<Permission> trees = new ArrayList<>();
  53. for (Permission treeNode : treeNodes) {
  54. if ("0".equals(treeNode.getPid())) {
  55. treeNode.setLevel(1);
  56. trees.add(findChildren(treeNode,treeNodes));
  57. }
  58. }
  59. return trees;
  60. }
  61. /**
  62. * 递归查找子节点
  63. * @param treeNodes
  64. * @return
  65. */
  66. private static Permission findChildren(Permission treeNode,List<Permission> treeNodes) {
  67. treeNode.setChildren(new ArrayList<Permission>());
  68. for (Permission it : treeNodes) {
  69. if(treeNode.getId().equals(it.getPid())) {
  70. int level = treeNode.getLevel() + 1;
  71. it.setLevel(level);
  72. if (treeNode.getChildren() == null) {
  73. treeNode.setChildren(new ArrayList<>());
  74. }
  75. treeNode.getChildren().add(findChildren(it,treeNodes));
  76. }
  77. }
  78. return treeNode;
  79. }

五、根据用户id获取用户菜单

1、PermissionService

  1. public interface PermissionService extends IService<Permission> {
  2. //根据用户id获取用户菜单
  3. List<String> selectPermissionValueByUserId(String id);
  4. }

2、PermissionServiceImpl

  1. //根据用户id获取用户菜单
  2. @Override
  3. public List<String> selectPermissionValueByUserId(String id) {
  4. List<String> selectPermissionValueList = null;
  5. if(this.isSysAdmin(id)) {
  6. // 如果是系统管理员,获取所有权限
  7. selectPermissionValueList = baseMapper.selectAllPermissionValue();
  8. } else {
  9. selectPermissionValueList = baseMapper.selectPermissionValueByUserId(id);
  10. }
  11. return selectPermissionValueList;
  12. }

3、PermissionMapper

  1. public interface PermissionMapper extends BaseMapper<Permission> {
  2. // 系统管理员,获取所有权限
  3. List<String> selectAllPermissionValue();
  4. // 非系统管理员,根据用户id获取用户菜单
  5. List<String> selectPermissionValueByUserId(String id);
  6. }

4、PermissionMapper.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  3. <mapper namespace="com.atguigu.aclservice.mapper.PermissionMapper">
  4. <resultMap id="permissionMap" type="com.atguigu.aclservice.entity.Permission">
  5. <result property="id" column="id"/>
  6. <result property="pid" column="pid"/>
  7. <result property="name" column="name"/>
  8. <result property="type" column="type"/>
  9. <result property="permissionValue" column="permission_value"/>
  10. <result property="path" column="path"/>
  11. <result property="component" column="component"/>
  12. <result property="icon" column="icon"/>
  13. <result property="status" column="status"/>
  14. <result property="isDeleted" column="is_deleted"/>
  15. <result property="gmtCreate" column="gmt_create"/>
  16. <result property="gmtModified" column="gmt_modified"/>
  17. </resultMap>
  18. <!-- 用于select查询公用抽取的列 -->
  19. <sql id="columns">
  20. p.id,p.pid,p.name,p.type,p.permission_value,path,p.component,p.icon,p.status,p.is_deleted,p.gmt_create,p.gmt_modified
  21. </sql>
  22. // 非系统管理员,根据用户id获取用户菜单
  23. <select id="selectPermissionValueByUserId" resultType="String">
  24. select
  25. p.permission_value
  26. from acl_user_role ur
  27. inner join acl_role_permission rp on rp.role_id = ur.role_id
  28. inner join acl_permission p on p.id = rp.permission_id
  29. where ur.user_id = #{userId}
  30. and p.type = 2
  31. and ur.is_deleted = 0
  32. and rp.is_deleted = 0
  33. and p.is_deleted = 0
  34. </select>
  35. // 系统管理员,获取所有权限
  36. <select id="selectAllPermissionValue" resultType="String">
  37. select
  38. permission_value
  39. from
  40. acl_permission
  41. where
  42. type = 2
  43. and is_deleted = 0
  44. </select>
  45. </mapper>

5、IndexServiceImpl

  1. /**
  2. * 根据用户名获取用户登录信息
  3. *
  4. * @param username
  5. * @return
  6. */
  7. public Map<String, Object> getUserInfo(String username) {
  8. Map<String, Object> result = new HashMap<>();
  9. User user = userService.selectByUsername(username);
  10. if (null == user) {
  11. //throw new GuliException(ResultCodeEnum.FETCH_USERINFO_ERROR);
  12. }
  13. //根据用户id获取角色
  14. List<Role> roleList = roleService.selectRoleByUserId(user.getId());
  15. List<String> roleNameList = roleList.stream().map(item -> item.getRoleName()).collect(Collectors.toList());
  16. if(roleNameList.size() == 0) {
  17. //前端框架必须返回一个角色,否则报错,如果没有角色,返回一个空角色
  18. roleNameList.add("");
  19. }
  20. //根据用户id获取操作权限值
  21. List<String> permissionValueList = permissionService.selectPermissionValueByUserId(user.getId());
  22. redisTemplate.opsForValue().set(username, permissionValueList);
  23. result.put("name", user.getUsername());
  24. result.put("avatar", "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
  25. result.put("roles", roleNameList);
  26. result.put("permissionValueList", permissionValueList);
  27. return result;
  28. }

6、IndexController

  1. /**
  2. * 根据token获取用户信息
  3. */
  4. @GetMapping("info")
  5. public R info(){
  6. //获取当前登录用户用户名
  7. String username = SecurityContextHolder.getContext().getAuthentication().getName();
  8. Map<String, Object> userInfo = indexService.getUserInfo(username);
  9. return R.ok().data(userInfo);
  10. }

六、根据用户id获取用户菜单权限

1、PermissionService

  1. public interface PermissionService extends IService<Permission> {
  2. //根据用户id获取用户菜单权限
  3. List<JSONObject> selectPermissionByUserId(String id);
  4. }

2、PermissionServiceImpl

  1. /**
  2. * 根据用户id获取用户菜单权限
  3. * @param userId
  4. * @return
  5. */
  6. @Override
  7. public List<JSONObject> selectPermissionByUserId(String userId) {
  8. List<Permission> selectPermissionList = null;
  9. if(this.isSysAdmin(userId)) {
  10. // 如果是超级管理员,获取所有菜单
  11. selectPermissionList = baseMapper.selectList(null);
  12. } else {
  13. selectPermissionList = baseMapper.selectPermissionByUserId(userId);
  14. }
  15. // 根据权限数据构建菜单数据
  16. List<Permission> permissionList = PermissionHelper.bulid(selectPermissionList);
  17. // 根据权限数据构建登录用户左侧菜单数据
  18. List<JSONObject> result = MemuHelper.bulid(permissionList);
  19. return result;
  20. }

1)PermissionHelper

  1. /**
  2. * 根据权限数据构建菜单数据
  3. */
  4. public class PermissionHelper {
  5. /**
  6. * 使用递归方法建菜单
  7. * @param treeNodes
  8. * @return
  9. */
  10. public static List<Permission> bulid(List<Permission> treeNodes) {
  11. List<Permission> trees = new ArrayList<>();
  12. for (Permission treeNode : treeNodes) {
  13. if ("0".equals(treeNode.getPid())) {
  14. treeNode.setLevel(1);
  15. trees.add(findChildren(treeNode,treeNodes));
  16. }
  17. }
  18. return trees;
  19. }
  20. /**
  21. * 递归查找子节点
  22. * @param treeNodes
  23. * @return
  24. */
  25. public static Permission findChildren(Permission treeNode,List<Permission> treeNodes) {
  26. treeNode.setChildren(new ArrayList<Permission>());
  27. for (Permission it : treeNodes) {
  28. if(treeNode.getId().equals(it.getPid())) {
  29. int level = treeNode.getLevel() + 1;
  30. it.setLevel(level);
  31. if (treeNode.getChildren() == null) {
  32. treeNode.setChildren(new ArrayList<>());
  33. }
  34. treeNode.getChildren().add(findChildren(it,treeNodes));
  35. }
  36. }
  37. return treeNode;
  38. }
  39. }

2)MemuHelper

  1. /**
  2. * 根据权限数据构建登录用户左侧菜单数据
  3. */
  4. public class MemuHelper {
  5. /**
  6. * 构建菜单
  7. * @param treeNodes
  8. * @return
  9. */
  10. public static List<JSONObject> bulid(List<Permission> treeNodes) {
  11. List<JSONObject> meuns = new ArrayList<>();
  12. if(treeNodes.size() == 1) {
  13. Permission topNode = treeNodes.get(0);
  14. //左侧一级菜单
  15. List<Permission> oneMeunList = topNode.getChildren();
  16. for(Permission one :oneMeunList) {
  17. JSONObject oneMeun = new JSONObject();
  18. oneMeun.put("path", one.getPath());
  19. oneMeun.put("component", one.getComponent());
  20. oneMeun.put("redirect", "noredirect");
  21. oneMeun.put("name", "name_"+one.getId());
  22. oneMeun.put("hidden", false);
  23. JSONObject oneMeta = new JSONObject();
  24. oneMeta.put("title", one.getName());
  25. oneMeta.put("icon", one.getIcon());
  26. oneMeun.put("meta", oneMeta);
  27. List<JSONObject> children = new ArrayList<>();
  28. List<Permission> twoMeunList = one.getChildren();
  29. for(Permission two :twoMeunList) {
  30. JSONObject twoMeun = new JSONObject();
  31. twoMeun.put("path", two.getPath());
  32. twoMeun.put("component", two.getComponent());
  33. twoMeun.put("name", "name_"+two.getId());
  34. twoMeun.put("hidden", false);
  35. JSONObject twoMeta = new JSONObject();
  36. twoMeta.put("title", two.getName());
  37. twoMeun.put("meta", twoMeta);
  38. children.add(twoMeun);
  39. List<Permission> threeMeunList = two.getChildren();
  40. for(Permission three :threeMeunList) {
  41. if(StringUtils.isEmpty(three.getPath())) continue;
  42. JSONObject threeMeun = new JSONObject();
  43. threeMeun.put("path", three.getPath());
  44. threeMeun.put("component", three.getComponent());
  45. threeMeun.put("name", "name_"+three.getId());
  46. threeMeun.put("hidden", true);
  47. JSONObject threeMeta = new JSONObject();
  48. threeMeta.put("title", three.getName());
  49. threeMeun.put("meta", threeMeta);
  50. children.add(threeMeun);
  51. }
  52. }
  53. oneMeun.put("children", children);
  54. meuns.add(oneMeun);
  55. }
  56. }
  57. return meuns;
  58. }
  59. }

3、PermissionMapper

  1. public interface PermissionMapper extends BaseMapper<Permission> {
  2. // 非超级管理员,根据用户id获取用户菜单权限
  3. List<Permission> selectPermissionByUserId(String userId);
  4. }

4、PermissionMapper.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  3. <mapper namespace="com.atguigu.aclservice.mapper.PermissionMapper">
  4. <resultMap id="permissionMap" type="com.atguigu.aclservice.entity.Permission">
  5. <result property="id" column="id"/>
  6. <result property="pid" column="pid"/>
  7. <result property="name" column="name"/>
  8. <result property="type" column="type"/>
  9. <result property="permissionValue" column="permission_value"/>
  10. <result property="path" column="path"/>
  11. <result property="component" column="component"/>
  12. <result property="icon" column="icon"/>
  13. <result property="status" column="status"/>
  14. <result property="isDeleted" column="is_deleted"/>
  15. <result property="gmtCreate" column="gmt_create"/>
  16. <result property="gmtModified" column="gmt_modified"/>
  17. </resultMap>
  18. <!-- 用于select查询公用抽取的列 -->
  19. <sql id="columns">
  20. p.id,p.pid,p.name,p.type,p.permission_value,path,p.component,p.icon,p.status,p.is_deleted,p.gmt_create,p.gmt_modified
  21. </sql>
  22. // 非超级管理员,根据用户id获取用户菜单权限
  23. <select id="selectPermissionByUserId" resultMap="permissionMap">
  24. select
  25. <include refid="columns" />
  26. from acl_user_role ur
  27. inner join acl_role_permission rp on rp.role_id = ur.role_id
  28. inner join acl_permission p on p.id = rp.permission_id
  29. where ur.user_id = #{userId}
  30. and ur.is_deleted = 0
  31. and rp.is_deleted = 0
  32. and p.is_deleted = 0
  33. </select>
  34. </mapper>

5、IndexServiceImpl

  1. /**
  2. * 根据用户名获取动态菜单
  3. * @param username
  4. * @return
  5. */
  6. public List<JSONObject> getMenu(String username) {
  7. User user = userService.selectByUsername(username);
  8. //根据用户id获取用户菜单权限
  9. List<JSONObject> permissionList = permissionService.selectPermissionByUserId(user.getId());
  10. return permissionList;
  11. }

6、IndexController

  1. /**
  2. * 获取菜单
  3. * @return
  4. */
  5. @GetMapping("menu")
  6. public R getMenu(){
  7. //获取当前登录用户用户名
  8. String username = SecurityContextHolder.getContext().getAuthentication().getName();
  9. List<JSONObject> permissionList = indexService.getMenu(username);
  10. return R.ok().data("permissionList", permissionList);
  11. }