【学生管理系统】权限管理之角色管理

简介: 【学生管理系统】权限管理之角色管理

6.3 角色管理

6.3.1 查询所有角色

1)后端【已有】

2)前端

  • 要求:左右分屏
<template>
  <div>
    <el-row>
      <el-col :span="16">
        <el-card class="role-list-card">
          <div slot="header" class="clearfix">
            <span>角色列表</span>
          </div>
          <!-- 角色列表 start -->
          <el-table
            :data="roleList"
            stripe
            style="width: 100%">
            <el-table-column
              prop="id"
              label="角色ID"
              fixed
              width="80">
            </el-table-column>
            <el-table-column
              prop="roleName"
              label="角色名称"
              fixed
              width="180">
            </el-table-column>
            <el-table-column
              prop="roleDesc"
              label="角色描述"
              width="200">
            </el-table-column>
            <el-table-column
              label="操作" 
              fixed="right">
              <template slot-scope="scope">
                <el-button size="mini">编辑</el-button>
                <el-button size="mini" type="danger">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 角色列表 end -->
        </el-card>
      </el-col>
      <el-col :span="8" style="padding-left: 10px;">
        <el-card class="perm-list-card">
          <div slot="header" class="clearfix">
            <span>权限展示</span>
            <el-button type="primary" style="float: right; padding: 3px 0">授权</el-button>
          </div>
          <!-- 权限展示 start -->
          <!-- 权限展示 end -->
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>
<script>
export default {
  data() {
    return {
      roleList: []
    }
  },
  methods: {
    async findAllRole() {
      // ajax
      let { data: baseResult } = await this.$axios.get('/user-service/role')
      // 处理
      if(baseResult.code == 20000) {
        this.roleList = baseResult.data
      } else {
        this.$message.error(baseResult.message)
      }
    }
  },
  mounted() {
    // 查询所有的角色
    this.findAllRole()
  },
}
</script>
<style>
  .role-list-card {
    height: 100%;
  }
  .perm-list-card {
    height: 100%;
  }
</style>

6.3.2 核心2:给角色授予权限(菜单)

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

  • 方式1:在controller中排序查询所有,然后使用Map进行缓存处理,将所有权限拼凑成父子关系。
  • 方式2:使用mapper注解版
  1. 编写PermMapper:查询指定父id的所有权限,需配置关联项(当前权限的所有的孩子)
  2. 编写service:查询所有
  3. 编写controller:查询所有
  1. 编写PermMapper:查询指定父id的所有权限,需配置关联项(当前权限的所有的孩子)
package com.czxy.classes.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.czxy.sys.SysPermission;
import org.apache.ibatis.annotations.*;
import java.util.List;
/**
 * @author 桐叔
 * @email liangtong@itcast.cn
 * @description
 */
@Mapper
public interface SysPermissionMapper extends BaseMapper<SysPermission> {
    /**
     * 通过父id查询所有的权限
     * @author 桐叔
     * @email liangtong@itcast.cn
     * @return
     */
    @Select("SELECT * FROM sys_permission WHERE parent_id = #{parentId}")
    @Results({
            @Result(property = "id", column = "id"),
            @Result(property = "permName", column = "permName"),
            @Result(property = "parentId", column = "parent_id"),
            @Result(property = "path", column = "path"),
            @Result(property = "children", many = @Many(select = "com.czxy.classes.mapper.SysPermissionMapper.findAllByParentId"), column = "id")
    })
    public List<SysPermission> findAllByParentId(@Param("parentId") Integer parentId) ;
}

编写service:查询所有

  • 接口
@Service
@Transactional
public interface SysPermissionService extends IService<SysPermission> {
    public List<SysPermission> findAllByParentId(Integer parentId) ;
}

实现类

package com.czxy.classes.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.czxy.classes.mapper.SysPermissionMapper;
import com.czxy.classes.service.SysPermissionService;
import com.czxy.sys.SysPermission;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
 * @author 桐叔
 * @email liangtong@itcast.cn
 * @description
 */
@Service
@Transactional
public class SysPermissionServiceImpl extends ServiceImpl<SysPermissionMapper, SysPermission> implements SysPermissionService {
    @Override
    public List<SysPermission> findAllByParentId(Integer parentId) {
        return baseMapper.findAllByParentId(parentId);
    }
}

编写controller:查询所有

package com.czxy.classes.controller;
import com.czxy.classes.service.SysPermissionService;
import com.czxy.sys.SysPermission;
import com.czxy.vo.BaseResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.List;
/**
 * @author 桐叔
 * @email liangtong@itcast.cn
 * @description
 */
@RestController
@RequestMapping("/perm")
public class SysPermissionController {
    @Resource
    private SysPermissionService sysPermissionService;
    /**
     * 查询所有,含孩子
     * @author 桐叔
     * @email liangtong@itcast.cn
     * @return
     */
    @GetMapping("/parent/{parentId}")
    public BaseResult findAllByParentId(@PathVariable("parentId") Integer parentId) {
        // 查询
        List<SysPermission> list = sysPermissionService.findAllByParentId(parentId);
        return BaseResult.ok("查询成功", list);
    }
}

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

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

2daace45e4de4166a270088410372a47.png

package com.czxy.classes.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.czxy.classes.service.SysRolePermissionService;
import com.czxy.sys.SysRolePermission;
import com.czxy.vo.BaseResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;
/**
 * @author 桐叔
 * @email liangtong@itcast.cn
 * @description
 */
@RestController
@RequestMapping("/rolePerm")
public class SysRolePermissionController {
    @Resource
    private SysRolePermissionService sysRolePermissionService;
    @GetMapping("/role/{roleId}")
    public BaseResult findAllByRoleId(@PathVariable("roleId") Integer roleId) {
        //1 条件 roleId = 1
        QueryWrapper<SysRolePermission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_id", roleId);
        //2 查询所有- 角色权限对象
        List<SysRolePermission> list = sysRolePermissionService.list(queryWrapper);
        //3 处理数据,只需要权限id
        List<Integer> roleIdList = list.stream().map(sysRolePermission -> sysRolePermission.getPermId()).collect(Collectors.toList());
        //4 返回
        return BaseResult.ok("查询成功", roleIdList);
    }
}

3)前端:展示所有的权限

  • 编写变量、发送ajax查询、页面加载成功时调用
  • 使用tree进行展示

a4f278abac0b41b98ca916bf4df40ca4.png

<template>
  <div>
    <el-row>
      <el-col :span="16">
        <el-card class="role-list-card">
          <div slot="header" class="clearfix">
            <span>角色列表</span>
          </div>
          <!-- 角色列表 start -->
          <el-table
            :data="roleList"
            stripe
            style="width: 100%">
            <el-table-column
              prop="id"
              label="角色ID"
              fixed
              width="80">
            </el-table-column>
            <el-table-column
              prop="roleName"
              label="角色名称"
              fixed
              width="180">
            </el-table-column>
            <el-table-column
              prop="roleDesc"
              label="角色描述"
              width="200">
            </el-table-column>
            <el-table-column
              label="操作" 
              fixed="right">
              <template slot-scope="scope">
                <el-button size="mini">编辑</el-button>
                <el-button size="mini" type="danger">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 角色列表 end -->
        </el-card>
      </el-col>
      <el-col :span="8" style="padding-left: 10px;">
        <el-card class="perm-list-card">
          <div slot="header" class="clearfix">
            <span>权限展示</span>
            <el-button type="primary" style="float: right; padding: 3px 0">授权</el-button>
          </div>
          <!-- 权限展示 start -->
          <el-tree
            :data="permList"
            show-checkbox
            default-expand-all
            node-key="id"
            ref="permTree"
            highlight-current
            :props="defaultProps">
          </el-tree>
          <!-- 权限展示 end -->
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>
<script>
export default {
  data() {
    return {
      roleList: [],               //角色列表
      permList: [],               //权限列表
      defaultProps: {             //tree提供的数据 与 所需数据 对应关系
        children: 'children',
        label: 'permName'
      }
    }
  },
  methods: {
    async findAllRole() {
      // ajax
      let { data: baseResult } = await this.$axios.get('/user-service/role')
      // 处理
      if(baseResult.code == 20000) {
        this.roleList = baseResult.data
      } else {
        this.$message.error(baseResult.message)
      }
    },
    async findAllPerm(parentId) {
      // ajax
      let { data: baseResult } = await this.$axios.get(`/user-service/perm/parent/${parentId}`)
      // 处理
      if(baseResult.code == 20000) {
        this.permList = baseResult.data
      } else {
        this.$message.error(baseResult.message)
      }
    }
  },
  mounted() {
    // 查询所有的角色
    this.findAllRole()
    // 查询所有的一级权限
    this.findAllPerm(0)
  },
}
</script>
<style>
  .role-list-card {
    height: 100%;
  }
  .perm-list-card {
    height: 100%;
  }
</style>

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

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

查询当前角色对应的所有选线,并回显到tree中

b4c1bd765bd84a30921097ad68ec8315.png

 async findAllPermByRoleId(row, column, event) {
      // ajax 查询   /user-service/rolePerm/role/1
      let { data: baseResult } = await this.$axios.get(`/user-service/rolePerm/role/${row.id}`)
      // 处理
      if(baseResult.code == 20000) {
        // 查询成功,将查询的结果填充到右侧tree中
        this.$refs.permTree.setCheckedKeys(baseResult.data);
      } else {
        this.$message.error(baseResult.message)
      }
    }
<template>
  <div>
    <el-row>
      <el-col :span="16">
        <el-card class="role-list-card">
          <div slot="header" class="clearfix">
            <span>角色列表</span>
          </div>
          <!-- 角色列表 start -->
          <el-table
            :data="roleList"
            stripe
            @row-click="findAllPermByRoleId"
            style="width: 100%">
            <el-table-column
              prop="id"
              label="角色ID"
              fixed
              width="80">
            </el-table-column>
            <el-table-column
              prop="roleName"
              label="角色名称"
              fixed
              width="180">
            </el-table-column>
            <el-table-column
              prop="roleDesc"
              label="角色描述"
              width="200">
            </el-table-column>
            <el-table-column
              label="操作" 
              fixed="right">
              <template slot-scope="scope">
                <el-button size="mini">编辑</el-button>
                <el-button size="mini" type="danger">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 角色列表 end -->
        </el-card>
      </el-col>
      <el-col :span="8" style="padding-left: 10px;">
        <el-card class="perm-list-card">
          <div slot="header" class="clearfix">
            <span>权限展示</span>
            <el-button type="primary" style="float: right; padding: 3px 0">授权</el-button>
          </div>
          <!-- 权限展示 start -->
          <el-tree
            :data="permList"
            show-checkbox
            default-expand-all
            node-key="id"
            ref="permTree"
            highlight-current
            :props="defaultProps">
          </el-tree>
          <!-- 权限展示 end -->
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>
<script>
export default {
  data() {
    return {
      roleList: [],               //角色列表
      permList: [],               //权限列表
      defaultProps: {             //tree提供的数据 与 所需数据 对应关系
        children: 'children',
        label: 'permName'
      }
    }
  },
  methods: {
    async findAllRole() {
      // ajax
      let { data: baseResult } = await this.$axios.get('/user-service/role')
      // 处理
      if(baseResult.code == 20000) {
        this.roleList = baseResult.data
      } else {
        this.$message.error(baseResult.message)
      }
    },
    async findAllPerm(parentId) {
      // ajax
      let { data: baseResult } = await this.$axios.get(`/user-service/perm/parent/${parentId}`)
      // 处理
      if(baseResult.code == 20000) {
        this.permList = baseResult.data
      } else {
        this.$message.error(baseResult.message)
      }
    },
    async findAllPermByRoleId(row, column, event) {
      // ajax 查询   /user-service/rolePerm/role/1
      let { data: baseResult } = await this.$axios.get(`/user-service/rolePerm/role/${row.id}`)
      // 处理
      if(baseResult.code == 20000) {
        // 查询成功,将查询的结果填充到右侧tree中
        this.$refs.permTree.setCheckedKeys(baseResult.data);
      } else {
        this.$message.error(baseResult.message)
      }
    }
  },
  mounted() {
    // 查询所有的角色
    this.findAllRole()
    // 查询所有的一级权限
    this.findAllPerm(0)
  },
}
</script>
<style>
  .role-list-card {
    height: 100%;
  }
  .perm-list-card {
    height: 100%;
  }
</style>

5)前端:提交授权表单

a9209d28d1584751998bba9324d32655.png

<template>
  <div>
    <el-row>
      <el-col :span="16">
        <el-card class="role-list-card">
          <div slot="header" class="clearfix">
            <span>角色列表</span>
          </div>
          <!-- 角色列表 start -->
          <el-table
            :data="roleList"
            stripe
            @row-click="findAllPermByRoleId"
            style="width: 100%">
            <el-table-column
              prop="id"
              label="角色ID"
              fixed
              width="80">
            </el-table-column>
            <el-table-column
              prop="roleName"
              label="角色名称"
              fixed
              width="180">
            </el-table-column>
            <el-table-column
              prop="roleDesc"
              label="角色描述"
              width="200">
            </el-table-column>
            <el-table-column
              label="操作" 
              fixed="right">
              <template slot-scope="scope">
                <el-button size="mini">编辑</el-button>
                <el-button size="mini" type="danger">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 角色列表 end -->
        </el-card>
      </el-col>
      <el-col :span="8" style="padding-left: 10px;">
        <el-card class="perm-list-card">
          <div slot="header" class="clearfix">
            <span>权限展示</span>
            <el-button type="primary" @click="addPermWithRoleId" style="float: right; padding: 3px 0">授权</el-button>
          </div>
          <!-- 权限展示 start -->
          <el-tree
            :data="permList"
            show-checkbox
            default-expand-all
            node-key="id"
            ref="permTree"
            highlight-current
            :props="defaultProps">
          </el-tree>
          <!-- 权限展示 end -->
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>
<script>
export default {
  data() {
    return {
      roleList: [],               //角色列表
      permList: [],               //权限列表
      defaultProps: {             //tree提供的数据 与 所需数据 对应关系
        children: 'children',
        label: 'permName'
      },
      role: {
        id: '',         //角色id
        permIds: []     //所选权限的id
      }
    }
  },
  methods: {
    async findAllRole() {
      // ajax
      let { data: baseResult } = await this.$axios.get('/user-service/role')
      // 处理
      if(baseResult.code == 20000) {
        this.roleList = baseResult.data
      } else {
        this.$message.error(baseResult.message)
      }
    },
    async findAllPerm(parentId) {
      // ajax
      let { data: baseResult } = await this.$axios.get(`/user-service/perm/parent/${parentId}`)
      // 处理
      if(baseResult.code == 20000) {
        this.permList = baseResult.data
      } else {
        this.$message.error(baseResult.message)
      }
    },
    async findAllPermByRoleId(row, column, event) {
      // ajax 查询   /user-service/rolePerm/role/1
      let { data: baseResult } = await this.$axios.get(`/user-service/rolePerm/role/${row.id}`)
      // 处理
      if(baseResult.code == 20000) {
        // 查询成功,将查询的结果填充到右侧tree中
        this.$refs.permTree.setCheckedKeys(baseResult.data);
        // 记录已有数据
        this.role.id = row.id
        this.role.permIds = baseResult.data
        console.info(this.role)
      } else {
        this.$message.error(baseResult.message)
      }
    },
    async addPermWithRoleId() {
      // 判断是否选择角色
      if(! this.role.id) {
        this.$message.warning('请先选择角色')
        return;
      }
      // 更新所选权限
      this.role.permIds = this.$refs.permTree.getCheckedKeys()
      // ajax 提交
      let { data: baseResult } = await this.$axios.post('/user-service/rolePerm/addPerm', this.role)
      // 提示
      if(baseResult.code == 20000) {
        this.$message.success(baseResult.message)
      } else {
        this.$message.error(baseResult.message)
      }
    }
  },
  mounted() {
    // 查询所有的角色
    this.findAllRole()
    // 查询所有的一级权限
    this.findAllPerm(0)
  },
}
</script>
<style>
  .role-list-card {
    height: 100%;
  }
  .perm-list-card {
    height: 100%;
  }
</style>

6)后端:授权

编写controller

编写service

编写controller


7cbb1b1e50504131885c47bb3bbeed10.png

  @PostMapping("/addPerm")
    public BaseResult addPermWithRoleId(@RequestBody SysRole sysRole) {
        try {
            // 添加权限
            sysRolePermissionService.addPermWithRoleId(sysRole);
            // 提示
            return BaseResult.ok("授权成功");
        } catch (Exception e) {
            return BaseResult.error("授权失败");
        }
    }

编写service


e2ceb437bc94420cb78300df292e7ee5.png 

  • 接口

@Service
@Transactional
public interface SysRolePermissionService extends IService<SysRolePermission> {
    void addPermWithRoleId(SysRole sysRole);
}

实现类

package com.czxy.classes.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.czxy.classes.mapper.SysRolePermissionMapper;
import com.czxy.classes.service.SysRolePermissionService;
import com.czxy.sys.SysRole;
import com.czxy.sys.SysRolePermission;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
 * @author 桐叔
 * @email liangtong@itcast.cn
 * @description
 */
@Service
@Transactional
public class SysRolePermissionServiceImpl extends ServiceImpl<SysRolePermissionMapper, SysRolePermission> implements SysRolePermissionService {
    @Override
    public void addPermWithRoleId(SysRole sysRole) {
        // 1 删除
        QueryWrapper<SysRolePermission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_id", sysRole.getId());
        baseMapper.delete(queryWrapper);
        // 2 添加
        for (Integer permId : sysRole.getPermIds()) {
            SysRolePermission sysRolePermission = new SysRolePermission(sysRole.getId(), permId);
            baseMapper.insert(sysRolePermission);
        }
    }
}

6.3.3 添加角色

相关文章
|
SQL 安全 关系型数据库
第03章 用户与权限管理
第03章 用户与权限管理
85 0
|
前端开发 NoSQL 中间件
【学生管理系统】权限管理
【学生管理系统】权限管理
123 0
【学生管理系统】权限管理
|
数据库 数据安全/隐私保护
【学生管理系统】权限管理之用户管理(一)
【学生管理系统】权限管理之用户管理
126 0
【学生管理系统】权限管理之用户管理(一)
|
前端开发 数据库 数据安全/隐私保护
【学生管理系统】权限管理之用户管理(二)
【学生管理系统】权限管理之用户管理
42 0
【学生管理系统】权限管理之用户管理(二)
|
数据安全/隐私保护
11-企业权限管理-角色操作
11-企业权限管理-角色操作
11-企业权限管理-角色操作
|
SQL Oracle 关系型数据库
用户和权限管理 | 学习笔记(一)
快速学习用户和权限管理
189 0
用户和权限管理 | 学习笔记(一)
|
SQL Oracle 关系型数据库
用户和权限管理 | 学习笔记(二)
快速学习用户和权限管理
139 0
用户和权限管理 | 学习笔记(二)
|
关系型数据库 MySQL 数据安全/隐私保护
开发指南—权限管理—角色权限管理
本文介绍角色权限管理相关语法级示例。 PolarDB-X兼容原生MySQL 8.0基于橘色的权限控制,请参见基于角色的权限控制。
120 0
|
SQL Java 数据库
权限管理系统(四)
前面我们做的小项目都是一个表的,业务代码也相对简单。现在我们来做一个权限管理系统,体验一下多表的业务逻辑,顺便巩固一下过滤器的知识。!
481 2
权限管理系统(四)
|
PHP 数据库 数据安全/隐私保护
简单权限管理设计
这套权限管理是配合Zend Framework设计的,用在其他地方的时候可以做些修改。
简单权限管理设计