• 【学生管理系统】权限管理之角色管理—查询所有角色并给角色授予权限(菜单)


    目录

    一、查询所有角色

    二、给角色授予权限(菜单)

    2.1 后端:查询所有的权限(含孩子)

    2.2 后端:查询指定角色的所有的权限

    2.3 前端:展示所有的权限

    2.4 前端:回显指定角色的权限

    2. 5 前端:提交授权表单

    2. 6 后端:角色权限进行修改授权【先删除之前权限,在添加所有已选权限】

    💟 创作不易,不妨点赞💚评论❤️收藏💙一下


    一、查询所有角色

    1.1后端【方法已有】

    1. @RestController
    2. @RequestMapping("/role")
    3. public class SysRoleController {
    4. @Resource
    5. private SysRoleService sysRoleService;
    6. @GetMapping
    7. public BaseResult findAll() {
    8. List list = sysRoleService.list();
    9. return BaseResult.ok("查询成功", list);
    10. }
    11. }

    1.2前端

    效果展示:要求角色和权限菜单左右分屏

    1. <template>
    2. <div>
    3. <el-row>
    4. <el-col :span="16">
    5. <el-card class="role-list-card">
    6. <div slot="header" class="clearfix">
    7. <span>角色列表span>
    8. div>
    9. <el-table
    10. :data="roleList"
    11. stripe
    12. style="width: 100%">
    13. <el-table-column
    14. prop="id"
    15. label="角色ID"
    16. fixed
    17. width="80">
    18. el-table-column>
    19. <el-table-column
    20. prop="roleName"
    21. label="角色名称"
    22. fixed
    23. width="180">
    24. el-table-column>
    25. <el-table-column
    26. prop="roleDesc"
    27. label="角色描述"
    28. width="200">
    29. el-table-column>
    30. <el-table-column
    31. label="操作"
    32. fixed="right">
    33. <template slot-scope="scope">
    34. <el-button size="mini">编辑el-button>
    35. <el-button size="mini" type="danger">删除el-button>
    36. template>
    37. el-table-column>
    38. el-table>
    39. el-card>
    40. el-col>
    41. <el-col :span="8" style="padding-left: 10px;">
    42. <el-card class="perm-list-card">
    43. <div slot="header" class="clearfix">
    44. <span>权限展示span>
    45. <el-button type="primary" style="float: right; padding: 3px 0">授权el-button>
    46. div>
    47. el-card>
    48. el-col>
    49. el-row>
    50. div>
    51. template>
    52. <script>
    53. export default {
    54. data() {
    55. return {
    56. roleList: []
    57. }
    58. },
    59. methods: {
    60. async findAllRole() {
    61. // ajax
    62. let { data: baseResult } = await this.$axios.get('/user-service/role')
    63. // 处理
    64. if(baseResult.code == 20000) {
    65. this.roleList = baseResult.data
    66. } else {
    67. this.$message.error(baseResult.message)
    68. }
    69. }
    70. },
    71. mounted() {
    72. // 查询所有的角色
    73. this.findAllRole()
    74. },
    75. }
    76. script>
    77. <style>
    78. .role-list-card {
    79. height: 100%;
    80. }
    81. .perm-list-card {
    82. height: 100%;
    83. }
    84. style>

    二、给角色授予权限(菜单)

    2.1 后端:查询所有的权限(含孩子)

    • 方式1:在controller中排序查询所有,然后使用Map进行缓存处理,将所有权限拼凑成父子关系。

    • 方式2:使用mapper注解版

      1. 编写PermMapper:查询指定父id的所有权限,需配置关联项(当前权限的所有的孩子)

      2. 编写service:查询所有

      3. 编写controller:查询所有

    1. 编写PermMapper:查询指定父id的所有权限,需配置关联项(当前权限的所有的孩子)

     
    
    1. @Mapper
    2. public interface SysPermissionMapper extends BaseMapper {
    3.    /**
    4.     * 通过父id查询所有的权限
    5.     * @author 桐叔
    6.     * @email liangtong@itcast.cn
    7.     * @return
    8.     */
    9.    @Select("SELECT * FROM sys_permission WHERE parent_id = #{parentId}")
    10.    @Results({
    11.            @Result(property = "id", column = "id"),
    12.            @Result(property = "permName", column = "permName"),
    13.            @Result(property = "parentId", column = "parent_id"),
    14.            @Result(property = "path", column = "path"),
    15.            @Result(property = "children", many = @Many(select = "com.czxy.classes.mapper.SysPermissionMapper.findAllByParentId"), column = "id")
    16.   })
    17.    public List findAllByParentId(@Param("parentId") Integer parentId) ;
    18. }

    2.编写service:查询所有

    接口

    1. @Service
    2. @Transactional
    3. public interface SysPermissionService extends IService {
    4.    public List findAllByParentId(Integer parentId) ;
    5. }

    实现类

    1. @Service
    2. @Transactional
    3. public class SysPermissionServiceImpl extends ServiceImpl implements SysPermissionService {
    4.    @Override
    5.    public List findAllByParentId(Integer parentId) {
    6.        return baseMapper.findAllByParentId(parentId);
    7.   }
    8. }
    3.编写controller:查询所有 
    
    1. @RestController
    2. @RequestMapping("/perm")
    3. public class SysPermissionController {
    4.    @Resource
    5.    private SysPermissionService sysPermissionService;
    6.    /**
    7.     * 查询所有,含孩子
    8.     * @author 桐叔
    9.     * @email liangtong@itcast.cn
    10.     * @return
    11.     */
    12.    @GetMapping("/parent/{parentId}")
    13.    public BaseResult findAllByParentId(@PathVariable("parentId") Integer parentId) {
    14.        // 查询
    15.        List list = sysPermissionService.findAllByParentId(parentId);
    16.        return BaseResult.ok("查询成功", list);
    17.   }
    18. }

    2.2 后端:查询指定角色的所有的权限

    • 提交数据:roleId = 1

    • 获得数据:[ {roleId: 1, permId: 1}, {roleId: 1, permId: 2}, ...] --> [1,2,3,4]

    1. @RestController
    2. @RequestMapping("/rolePerm")
    3. public class SysRolePermissionController {
    4.    @Resource
    5.    private SysRolePermissionService sysRolePermissionService;
    6.    @GetMapping("/role/{roleId}")
    7.    public BaseResult findAllByRoleId(@PathVariable("roleId") Integer roleId) {
    8.        //1 条件 roleId = 1
    9.        QueryWrapper queryWrapper = new QueryWrapper<>();
    10.        queryWrapper.eq("role_id", roleId);
    11.        //2 查询所有- 角色权限对象
    12.        List list = sysRolePermissionService.list(queryWrapper);
    13.        //3 处理数据,只需要权限id
    14.        List roleIdList = list.stream().map(sysRolePermission -> sysRolePermission.getPermId()).collect(Collectors.toList());
    15.        //4 返回
    16.        return BaseResult.ok("查询成功", roleIdList);
    17.   }
    18. }

    2.3 前端:展示所有的权限

    • 编写变量、发送ajax查询、页面加载成功时调用

    • 使用tree进行展示

    1. <template>
    2.  <div>
    3.    <el-row>
    4.      <el-col :span="16">
    5.        <el-card class="role-list-card">
    6.          <div slot="header" class="clearfix">
    7.            <span>角色列表span>
    8.          div>
    9.          
    10.          
    11.        el-card>
    12.      el-col>
    13.      <el-col :span="8" style="padding-left: 10px;">
    14.        <el-card class="perm-list-card">
    15.          <div slot="header" class="clearfix">
    16.            <span>权限展示span>
    17.            <el-button type="primary" style="float: right; padding: 3px 0">授权el-button>
    18.          div>
    19.          
    20.          <el-tree
    21.            :data="permList"
    22.            show-checkbox
    23.            default-expand-all
    24.            node-key="id"
    25.            ref="permTree"
    26.            highlight-current
    27.            :props="defaultProps">
    28.          el-tree>
    29.          
    30.        el-card>
    31.        
    32.      el-col>
    33.    el-row>
    34.  div>
    35. template>
    36. <script>
    37. export default {
    38.  data() {
    39.    return {
    40.      roleList: [],               //角色列表
    41.      permList: [],               //权限列表
    42.      defaultProps: {             //tree提供的数据 与 所需数据 对应关系
    43.        children: 'children',
    44.        label: 'permName'
    45.     }
    46.   }
    47. },
    48.  methods: {
    49. //获取所有角色
    50.    async findAllRole() {
    51.      // ajax
    52.      let { data: baseResult } = await this.$axios.get('/user-service/role')
    53.      // 处理
    54.      if(baseResult.code == 20000) {
    55.        this.roleList = baseResult.data
    56.     } else {
    57.        this.$message.error(baseResult.message)
    58.     }
    59.   },
    60. //获取所有的一级权限及孩子
    61.    async findAllPerm(parentId) {
    62.      // ajax
    63.      let { data: baseResult } = await this.$axios.get(`/user-service/perm/parent/${parentId}`)
    64.      // 处理
    65.      if(baseResult.code == 20000) {
    66.        this.permList = baseResult.data
    67.     } else {
    68.        this.$message.error(baseResult.message)
    69.     }
    70.   }
    71. },
    72.  mounted() {
    73.    // 查询所有的角色
    74.    this.findAllRole()
    75.    // 查询所有的一级权限
    76.    this.findAllPerm(0)
    77. },
    78. }
    79. script>
    80. <style>
    81.  .role-list-card {
    82.    height: 100%;
    83. }
    84.  .perm-list-card {
    85.    height: 100%;
    86. }
    87. style>

    2.4 前端:回显指定角色的权限

    页面效果演示:

    • 表格行的点击,并获得当前行的数据

    • 查询当前角色对应的所有选项,并回显到tree中。点击角色行,获取对应的权限并勾选。

    表格及树形控件中的方法绑定及属性设置,请按照图片在对应位置进行设置

    1. //查询对应角色的权限
    2. async findAllPermByRoleId(row, column, event) {
    3. // ajax 查询 /user-service/rolePerm/role/1
    4. let { data: baseResult } = await this.$axios.get(`/user-service/rolePerm/role/${row.id}`)
    5. // 处理
    6. if(baseResult.code == 20000) {
    7. // 查询成功,将查询的结果填充到右侧tree中
    8. this.$refs.permTree.setCheckedKeys(baseResult.data);
    9. } else {
    10. this.$message.error(baseResult.message)
    11. }
    12. }

    2. 5 前端:提交授权表单

    1. //查询对应角色的权限
    2. //对点击过角色所在行的操作,对角色id进行记录
    3. async findAllPermByRoleId(row, column, event) {
    4.      // ajax 查询   /user-service/rolePerm/role/1
    5.      let { data: baseResult } = await this.$axios.get(`/user-service/rolePerm/role/${row.id}`)
    6.      // 处理
    7.      if(baseResult.code == 20000) {
    8.        // 查询成功,将查询的结果填充到右侧tree中
    9.        this.$refs.permTree.setCheckedKeys(baseResult.data);
    10.        // 记录已有数据
    11.        this.role.id = row.id
    12.        this.role.permIds = baseResult.data
    13.        console.info(this.role)
    14.     } else {
    15.        this.$message.error(baseResult.message)
    16.     }
    17.   },
    18. //判断是否点击过角色行,并进行提示
    19. //对角色的权限进行修改
    20.    async addPermWithRoleId() {
    21.      // 判断是否选择角色
    22.      if(! this.role.id) {
    23.        this.$message.warning('请先选择角色')
    24.        return;
    25.     }
    26.      // 更新所选权限
    27.      this.role.permIds = this.$refs.permTree.getCheckedKeys()
    28.      // ajax 提交
    29.      let { data: baseResult } = await this.$axios.post('/user-service/rolePerm/addPerm', this.role)
    30.      // 提示
    31.      if(baseResult.code == 20000) {
    32.        this.$message.success(baseResult.message)
    33.     } else {
    34.        this.$message.error(baseResult.message)
    35.     }
    36.   }

    2. 6 后端:角色权限进行修改授权【先删除之前权限,在添加所有已选权限】

    • 编写controller

    1.  @PostMapping("/addPerm")
    2.    public BaseResult addPermWithRoleId(@RequestBody SysRole sysRole) {
    3.        try {
    4.            // 添加权限
    5.            sysRolePermissionService.addPermWithRoleId(sysRole);
    6.            // 提示
    7.            return BaseResult.ok("授权成功");
    8.       } catch (Exception e) {
    9.            return BaseResult.error("授权失败");
    10.       }
    11.   }
    • 编写service

     接口

    1. @Service
    2. @Transactional
    3. public interface SysRolePermissionService extends IService {
    4.    void addPermWithRoleId(SysRole sysRole);
    5. }

    实现类

    1. @Service
    2. @Transactional
    3. public class SysRolePermissionServiceImpl extends ServiceImpl implements SysRolePermissionService {
    4.    @Override
    5.    public void addPermWithRoleId(SysRole sysRole) {
    6.        // 1 删除
    7.        QueryWrapper queryWrapper = new QueryWrapper<>();
    8.        queryWrapper.eq("role_id", sysRole.getId());
    9.        baseMapper.delete(queryWrapper);
    10.        // 2 添加
    11.        for (Integer permId : sysRole.getPermIds()) {
    12.            SysRolePermission sysRolePermission = new SysRolePermission(sysRole.getId(), permId);
    13.            baseMapper.insert(sysRolePermission);
    14.       }
    15.   }
    16. }

    写到最后

    四季轮换,已经数不清凋零了多少, 愿我们往后能向心而行,一路招摇胜!

    🐋 你的支持认可是我创作的动力

    💟 创作不易,不妨点赞💚评论❤️收藏💙一下

    😘 感谢大佬们的支持,欢迎各位前来不吝赐教

  • 相关阅读:
    Windows如何设置Tomcat开机启动?
    40 道基础Dubbo 面试题及答案
    单臂路由学习
    泊车功能专题介绍 ———— AVP系统基础数据交互内容
    MySQL高级篇第一章(linux下安装MySQL)【下】
    C语言中指针的介绍
    Discuz中的关键全局变量`$_G`
    向量数据库Pinecone,治疗ChatGPT幻觉的药方?
    【C++数据结构】程序性能分析
    ubuntu 安装串口工具和添加虚拟串口
  • 原文地址:https://blog.csdn.net/zsy3757486/article/details/127704974