前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【学生管理系统】权限管理之用户管理

【学生管理系统】权限管理之用户管理

作者头像
陶然同学
发布2023-02-24 15:16:10
1.2K0
发布2023-02-24 15:16:10
举报
文章被收录于专栏:陶然同学博客

目录

6. 权限管理

6.1 环境搭建

6.1.1 数据库

6.1.2 后端环境

6.2 用户管理

6.2.1 查询所有用户(关联角色)

6.2.2 核心1:给用户授予角色

6. 权限管理

6.1 环境搭建

6.1.1 数据库

  • 权限管理的5张表的关系
  • 添加4张表
代码语言:javascript
复制
# 权限表(菜单表)
CREATE TABLE `sys_permission`  (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `permName` varchar(50) ,
  `parent_id` int(11) ,
  `path` varchar(255) ,
  PRIMARY KEY (`id`) USING BTREE
);
​
INSERT INTO `sys_permission` VALUES (1, '班级管理', 0, '/classes');
INSERT INTO `sys_permission` VALUES (2, '添加班级', 1, '/classes/classesAdd');
INSERT INTO `sys_permission` VALUES (3, '班级列表', 1, '/classes/classesList');
​
INSERT INTO `sys_permission` VALUES (4, '学生管理', 0, '/student');
INSERT INTO `sys_permission` VALUES (5, '学生列表', 4, '/student/studentList');
​
INSERT INTO `sys_permission` VALUES (6, '权限管理', 0, '/perm');
INSERT INTO `sys_permission` VALUES (7, '权限列表', 6, '/perm/permissionList');
INSERT INTO `sys_permission` VALUES (8, '角色列表', 6, '/perm/roleList');
INSERT INTO `sys_permission` VALUES (9, '用户列表', 6, '/perm/userList');
​
​
# 角色表
CREATE TABLE `sys_role`  (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `roleName` varchar(50),
  `roleDesc` varchar(50),
  PRIMARY KEY (`id`) USING BTREE
) ;
​
INSERT INTO `sys_role` VALUES (1, 'admin', '超级管理员');
INSERT INTO `sys_role` VALUES (2, 'sms_admin', 'sms管理员');
INSERT INTO `sys_role` VALUES (3, 'user', '普通用户');
​
​
​
#中间表:角色权限表
CREATE TABLE `sys_role_permission`  (
  `role_id` int(10),
  `perm_id` int(10),
  INDEX `FK_Reference_3`(`role_id`) USING BTREE,
  INDEX `FK_Reference_4`(`perm_id`) USING BTREE,
  CONSTRAINT `sys_role_permission_ibfk_1` FOREIGN KEY (`perm_id`) REFERENCES `sys_permission` (`id`) ,
  CONSTRAINT `sys_role_permission_ibfk_2` FOREIGN KEY (`role_id`) REFERENCES `sys_role` (`id`) 
);
​
​
INSERT INTO `sys_role_permission` VALUES (1, 1);
INSERT INTO `sys_role_permission` VALUES (1, 2);
INSERT INTO `sys_role_permission` VALUES (1, 3);
INSERT INTO `sys_role_permission` VALUES (1, 4);
INSERT INTO `sys_role_permission` VALUES (1, 5);
INSERT INTO `sys_role_permission` VALUES (1, 6);
INSERT INTO `sys_role_permission` VALUES (1, 7);
INSERT INTO `sys_role_permission` VALUES (1, 8);
INSERT INTO `sys_role_permission` VALUES (1, 9);
​
INSERT INTO `sys_role_permission` VALUES (2, 1);
INSERT INTO `sys_role_permission` VALUES (2, 2);
INSERT INTO `sys_role_permission` VALUES (2, 3);
INSERT INTO `sys_role_permission` VALUES (2, 4);
INSERT INTO `sys_role_permission` VALUES (2, 5);
​
​
# 中间表:用户角色表
CREATE TABLE `sys_user_role`  (
  `user_id` VARCHAR(32),
  `role_id` INT(10) ,
  INDEX `FK_Reference_1`(`user_id`) USING BTREE,
  INDEX `FK_Reference_2`(`role_id`) USING BTREE,
  CONSTRAINT `sys_user_role_ibfk_1` FOREIGN KEY (`role_id`) REFERENCES `sys_role` (`id`),
  CONSTRAINT `sys_user_role_ibfk_2` FOREIGN KEY (`user_id`) REFERENCES `tb_user` (`u_id`)
);
​
INSERT INTO `sys_user_role` VALUES ('u001', 1);
INSERT INTO `sys_user_role` VALUES ('u001', 2);
INSERT INTO `sys_user_role` VALUES ('u002', 2);
​

6.1.2 后端环境

  • 基本内容:JavaBean、Mapper、Service、Controller
    • JavaBean
    • 基本结构

6.2 用户管理

6.2.1 查询所有用户(关联角色)

1)后端

  • 修改javaBean:List<SysRole> roleList
  • 编写Mapper:使用注解的方式查询关联数据
  • 编写Service
  • 编写Controller
  • 修改javaBean:List<SysRole> roleList
  • 编写Mapper:使用注解的方式查询关联数据
    • 修改UserMapper:查询所有,含角色

    package com.czxy.classes.mapper; ​ import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.czxy.domain.TbUser; import org.apache.ibatis.annotations.*; ​ import java.util.List; ​ /** * @author 桐叔 * @email liangtong@itcast.cn * @description */ @Mapper public interface TbUserMapper extends BaseMapper<TbUser> { ​    @Select("SELECT * FROM tb_user")    @Results({            @Result(property = "uid", column = "u_id"),            @Result(property = "userName", column = "user_name"),            @Result(property = "password", column = "password"),            @Result(property = "gender", column = "gender"),            @Result(property = "image", column = "image"),            @Result(property = "roleList", many = @Many(select = "com.czxy.classes.mapper.SysRoleMapper.findAllByUid") , column = "u_id")   })    public List<TbUser> findAll(); } ​

    • 修改RoleMapper:查询指定用户的角色

    package com.czxy.classes.mapper; ​ import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.czxy.sys.SysRole; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; ​ import java.util.List; ​ /** * @author 桐叔 * @email liangtong@itcast.cn * @description */ @Mapper public interface SysRoleMapper extends BaseMapper<SysRole> {    /**     * 查询指定用户的所有角色     * @author 桐叔     * @email liangtong@itcast.cn     * @return     */    @Select("SELECT r.* FROM sys_role r, sys_user_role ur WHERE r.id = ur.role_id AND ur.user_id = #{uid}")    public List<SysRole> findAllByUid(@Param("uid") String uid); } ​

  • 编写Service package com.czxy.classes.service; ​ import com.baomidou.mybatisplus.extension.service.IService; import com.czxy.domain.TbUser; ​ import java.util.List; ​ /** * @author 桐叔 * @email liangtong@itcast.cn * @description */ public interface TbUserService extends IService<TbUser> { ​    public List<TbUser> findAll(); } ​ 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.domain.TbUser; import com.czxy.classes.mapper.TbUserMapper; import com.czxy.classes.service.TbUserService; 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 TbUserServiceImpl extends ServiceImpl<TbUserMapper, TbUser> implements TbUserService { ​    @Override    public List<TbUser> findAll() {        return baseMapper.findAll();   } } ​
  • 编写Controller package com.czxy.classes.controller; ​ import com.czxy.classes.config.JwtProperties; import com.czxy.classes.utils.JwtUtils; import com.czxy.domain.TbUser; import com.czxy.classes.service.TbUserService; import com.czxy.vo.BaseResult; import org.springframework.web.bind.annotation.*; ​ import javax.annotation.Resource; import java.util.List; ​ /** * @author 桐叔 * @email liangtong@itcast.cn * @description */ @RestController @RequestMapping("/user") public class TbUserController {    @Resource    private TbUserService tbUserService; ​    @GetMapping    public BaseResult findAll() {        List<TbUser> list = tbUserService.findAll();        return BaseResult.ok("查询成功", list);   } ​ ​ } ​

2)前端

代码语言:javascript
复制
<template>
  <div>
    <!-- 列表start -->
    <el-table
      :data="userList"
      stripe
      style="width: 100%">
      <el-table-column
        type="selection"
        width="55">
      </el-table-column>
      <el-table-column
        prop="uid"
        label="用户ID"
        fixed
        width="80">
      </el-table-column>
      <el-table-column
        prop="userName"
        label="姓名"
        fixed
        width="100">
      </el-table-column>
      <el-table-column
        prop="gender"
        label="性别"
        width="80">
        <template slot-scope="scope">
          {{scope.row.gender == 1 ? '男': '女'}}
        </template>
      </el-table-column>
      <el-table-column
        prop="image"
        label="头像"
        width="80">
        <template slot-scope="scope">
          <el-avatar size="20" :src="scope.row.image"></el-avatar>
        </template>
      </el-table-column>
      <el-table-column
        label="角色"
        width="300">
        <template slot-scope="scope">
          <el-tag v-for="(role,index) in scope.row.roleList" :key="index" closable>{{role.roleName}}</el-tag>
        </template>
      </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 -->
  </div>
</template>
​
<script>
export default {
  data() {
    return {
      userList: []
    }
  },
  methods: {
    async findAllUser() {
      // ajax
      let { data: baseResult } = await this.$axios.get('/user-service/user')
      // 处理
      if(baseResult.code == 20000) {
        this.userList = baseResult.data
      } else {
        this.$message.error(baseResult.message)
      }
    },
  },
  mounted() {
    // 查询所有的用户
    this.findAllUser()
  },
}
</script>
​
<style>
​
</style>

6.2.2 核心1:给用户授予角色

1)分析

  • 前置功能:查询所有的角色
    • 后端:查询所有
    • 前端:下拉列表展示
  • 核心:给用户授予角色
    • 完成修改的部分功能,将用户选择的角色更新到数据库(先删除、后添加)
    • 后端:用户角色直接操作,给一个用户,添加一组角色
    • 前端:弹出框,直接使用table中的数据填充前端额下拉列表

2)前置功能:查询所有的角色-后端

代码语言:javascript
复制
package com.czxy.classes.controller;
​
import com.czxy.classes.service.SysRoleService;
import com.czxy.sys.SysRole;
import com.czxy.vo.BaseResult;
import org.springframework.web.bind.annotation.GetMapping;
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("/role")
public class SysRoleController {
    @Resource
    private SysRoleService sysRoleService;
​
    @GetMapping
    public BaseResult findAll() {
        List<SysRole> list = sysRoleService.list();
        return BaseResult.ok("查询成功", list);
    }
​
​
}
​

3)核心:给用户授予角色-后端

  • 用户角色直接操作,给一个用户,添加一组角色
  • 编写mapper:通过uid删除关联信息
  • 编写service:先删除后,后添加
  • 编写controller
  • 编写mapper:通过uid删除关联信息

package com.czxy.classes.mapper; ​ import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.czxy.sys.SysRole; import com.czxy.sys.SysUserRole; import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; ​ /** * @author 桐叔 * @email liangtong@itcast.cn * @description */ @Mapper public interface SysUserRoleMapper extends BaseMapper<SysUserRole> {    @Delete("DELETE FROM sys_user_role WHERE user_id = #{uid}")    int deleteByUid(@Param("uid") String uid); } ​

  • 编写service:先删除后,后添加

package com.czxy.classes.service; ​ import com.baomidou.mybatisplus.extension.service.IService; import com.czxy.domain.TbUser; import com.czxy.sys.SysUserRole; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; ​ /** * @author 桐叔 * @email liangtong@itcast.cn * @description */ @Service @Transactional public interface SysUserRoleService extends IService<SysUserRole> {    /**     * 给指定用户收取角色     * @author 桐叔     * @email liangtong@itcast.cn     * @return     */    void addRoleWithUser(TbUser tbUser); } ​ package com.czxy.classes.service.impl; ​ import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.czxy.classes.mapper.SysUserRoleMapper; import com.czxy.classes.service.SysUserRoleService; import com.czxy.domain.TbUser; import com.czxy.sys.SysUserRole; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; ​ /** * @author 桐叔 * @email liangtong@itcast.cn * @description */ @Service @Transactional public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleMapper, SysUserRole> implements SysUserRoleService { ​    @Override    public void addRoleWithUser(TbUser tbUser) { ​        //1 删除        baseMapper.deleteByUid(tbUser.getUid()); ​        //2 添加        for (Integer roleId : tbUser.getRoleIds()) {            SysUserRole sysUserRole = new SysUserRole(tbUser.getUid(), roleId);            baseMapper.insert(sysUserRole);       }   } } ​

  • 编写controller

package com.czxy.classes.controller; ​ import com.czxy.classes.service.SysUserRoleService; import com.czxy.domain.TbUser; import com.czxy.vo.BaseResult; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; ​ import javax.annotation.Resource; ​ /** * @author 桐叔 * @email liangtong@itcast.cn * @description */ @RestController @RequestMapping("/userRole") public class SysUserRoleController {    @Resource    private SysUserRoleService sysUserRoleService; ​    @PostMapping("/addRoleWithUser")    public BaseResult addRoleWithUser(@RequestBody TbUser tbUser) {        // 给用户添加角色        sysUserRoleService.addRoleWithUser(tbUser);        return BaseResult.ok("授权成功");   } ​ ​ } ​

4)前置功能:查询所有的角色-后端

5)核心:给用户授予角色-前端

代码语言:javascript
复制
<template>
  <div>
    <!-- 列表start -->
    <el-table
      :data="userList"
      stripe
      style="width: 100%">
      <el-table-column
        type="selection"
        width="55">
      </el-table-column>
      <el-table-column
        prop="uid"
        label="用户ID"
        fixed
        width="80">
      </el-table-column>
      <el-table-column
        prop="userName"
        label="姓名"
        fixed
        width="100">
      </el-table-column>
      <el-table-column
        prop="gender"
        label="性别"
        width="80">
        <template slot-scope="scope">
          {{scope.row.gender == 1 ? '男': '女'}}
        </template>
      </el-table-column>
      <el-table-column
        prop="image"
        label="头像"
        width="80">
        <template slot-scope="scope">
          <el-avatar :size="20" :src="scope.row.image"></el-avatar>
        </template>
      </el-table-column>
      <el-table-column
        label="角色"
        width="300">
        <template slot-scope="scope">
          <el-tag v-for="(role,index) in scope.row.roleList" :key="index" closable>{{role.roleName}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="操作" 
        fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" @click="openRoleDialog(scope.row)">授权</el-button>
          <el-button size="mini">编辑</el-button>
          <el-button size="mini" type="danger">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 列表end -->
​
    
    <!-- 弹出框 start -->
    <el-dialog title="授权" :visible.sync="dialogRoleVisible">
      <el-form :model="user" label-width="80px">
        <el-form-item label="角色列表">
          <el-select v-model="user.roleIds" multiple placeholder="请选择角色">
            <el-option v-for="(role,index) in roleList" :key="index" :label="role.roleName" :value="role.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      {{user}}
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogRoleVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoleWithUser">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 弹出框 end -->
  </div>
</template>
​
<script>
export default {
  data() {
    return {
      userList: [],
      dialogRoleVisible: false,
      user: {},
      roleList: []
    }
  },
  methods: {
    async findAllUser() {
      // ajax
      let { data: baseResult } = await this.$axios.get('/user-service/user')
      // 处理
      if(baseResult.code == 20000) {
        this.userList = baseResult.data
      } else {
        this.$message.error(baseResult.message)
      }
    },
    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)
      }
    },
    openRoleDialog(user) {
      // 查询所有角色
      this.findAllRole()
      // 填充表单
      this.user.uid = user.uid
      // 处理数据:从role对象过滤出role.id
      // this.user.roleIds = user.roleList.map(role => role.id)   //只能回显,不能操作
      this.$set(this.user, 'roleIds', user.roleList.map(role => role.id))
      // 打开弹出框
      this.dialogRoleVisible = true
    },
    async addRoleWithUser() {
      // ajax
      let { data: baseResult } = await this.$axios.post('/user-service/userRole/addRoleWithUser', this.user)
      // 处理
      if(baseResult.code == 20000) {
        // 成功
        this.$message.success(baseResult.message)
        // 刷新页面
        this.findAllUser()
        // 关闭弹出框
        this.dialogRoleVisible = false
      } else {
        this.$message.error(baseResult.message)
      }
    }
  },
  mounted() {
    // 查询所有的用户
    this.findAllUser()
  },
}
</script>
​
<style>
​
</style>
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-10-21,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 6. 权限管理
    • 6.1 环境搭建
      • 6.1.1 数据库
      • 6.1.2 后端环境
    • 6.2 用户管理
      • 6.2.1 查询所有用户(关联角色)
      • 6.2.2 核心1:给用户授予角色
相关产品与服务
访问管理
访问管理(Cloud Access Management,CAM)可以帮助您安全、便捷地管理对腾讯云服务和资源的访问。您可以使用CAM创建子用户、用户组和角色,并通过策略控制其访问范围。CAM支持用户和角色SSO能力,您可以根据具体管理场景针对性设置企业内用户和腾讯云的互通能力。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档