(1)点击分配角色应该需要查询以下
查询所有的角色进行弹框回显所有的角色
查询用户具有的角色id进行回显以及被勾选的复选框
具体需求: 显示出分配角色的弹出框时 列出所有的角色以及该用户具有的角色应该被选择。
确认分配角色 userID 以及被选中的角色id
要先删除该用户具有的角色 添加新的该用户具有的角色信息
<el-dialog title="分配角色" @click="" :visible.sync="fenFormVisible">
<el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选el-checkbox>
<div style="margin: 15px 0;">div>
<el-checkbox-group v-model="checkedRoles" @change="handlecheckedRolesChange">
<el-checkbox v-for="role in roles" :label="role.id" :key="role.id">{
{role.roleName}}el-checkbox>
el-checkbox-group>
<div slot="footer" class="dialog-footer">
<el-button @click="cancel1">取 消el-button>
<el-button type="primary" @click="confirmRole">确 定
el-button>
div>
el-dialog>
indeterminate 属性用以表示 checkbox 的不确定状态,一般用于实现全选的效果
//分配角色的弹出框默认值
fenFormVisible: false,
checkAll: false,
//被选中的
checkedRoles: [],
//全部的数据
roles: [],
//定义userid
userId:"",
//表示 checkbox 的不确定状态
isIndeterminate: true
分配权限的按钮,再这里需要传入当前行用户的id
==
//用户点击分配角色的按钮
fanPermission(userId) {
//开启弹出框
this.fenFormVisible = true;
this.userId=userId;
var that=this;
this.$http.get(`/aaa/role/findRoleByUserId/${userId}`).then(function (resp) {
//把后台查到的所以权限放入roles中
that.roles=resp.data.result.allRole;
that.checkedRoles=resp.data.result.userRoleId;
})
},
点击确认按钮需要传入 userID 以及被选中的角色id
后台操作: 删除该用户具有的角色 添加新的该用户具有的角色信息
//分配角色弹出框中的确认按钮
confirmRole(){
//分配角色 把被选中所有角色id传到后台,用户id
this.$http.post('/aaa/role/fenUserRole',{userId:this.userId,roleIds:this.checkedRoles}).then(function (resp) {
//关闭弹出框
this.fenFormVisible = false;
})
},
cancel1() {
//设置弹出框为关闭状态
this.fenFormVisible = false;
},
//全选的操作
handleCheckAllChange(val) {
//先把被选中的角色Id清空
this.checkedRoles=[];
// 如果为true
if (val){
// 循环将全部的角色id放入到被选中的数组中
this.roles.forEach(item=>{
this.checkedRoles.push(item.id);
})
}
// this.checkedRoles = val ? this.roles : [];
this.isIndeterminate = false;
},
handlecheckedRolesChange(value) {
let checkedCount = value.length;
this.checkAll = checkedCount === this.roles.length;
this.isIndeterminate = checkedCount > 0 && checkedCount < this.roles.length;
}
@RestController
@RequestMapping("/aaa/role")
@Api("角色的接口信息")
@CrossOrigin//解决跨域问题
public class RoleController {
@Resource
private RoleService roleService;
/**
* 根据用户id分配角色
*
* @param userid
* @return
*/
@GetMapping("/findRoleByUserId/{userid}")
public CommonResult findRoleByUserId(@PathVariable("userid") String userid) {
return roleService.findRoleByUserId(userid);
}
/**
* 根据用户id
* 给用户分配角色
* @return
*/
@PostMapping("/fenUserRole")
public CommonResult fenUserRole(@RequestBody UserRoleVo userRoleVo) {
System.out.println(userRoleVo);
return roleService.fenUserRole(userRoleVo);
}
}
注意这里用到了事务@Transactional声明式事务管理
必须要在主启动类上添加@EnableTransactionManagement//事务
后台分配角色:① 查询所有的角色 ②查询用户具有的角色id
后台添加角色:①删除用户的角色 ②循环添加用户的角色
@Service
public class RoleServiceImpl extends ServiceImpl<RoleDao, Role> implements RoleService {
@Resource
private RoleDao roleDao;
@Resource
private UserRoleDao userRoleDao;
@Transactional//声明式事务管理
@Override
public CommonResult findRoleByUserId(String userid) {
// 查询所有的角色
List<Role> roles = roleDao.selectList(null);
// 查询用户具有的角色id
QueryWrapper<UserRole> wrapper = new QueryWrapper<>();
wrapper.eq("user_id", userid);
List<UserRole> userRoles = userRoleDao.selectList(wrapper);
// R apply(T t);
// 通过stream流获取所有的roleid的值存放到list
List<String> userRoleId = userRoles.stream().map(item -> item.getRoleId()).collect(Collectors.toList());
System.out.println(userRoleId);
// 把所有的角色和角色id存放到map中返回到前台
HashMap<String, Object> map = new HashMap<>();
map.put("allRole", roles);
map.put("userRoleId", userRoleId);
return new CommonResult(2000, "查询成功", map);
}
/**
* 添加用户角色
* 先删除再批量添加
* @return
*/
@Transactional
@Override
public CommonResult fenUserRole(UserRoleVo userRoleVo) {
//删除用户的角色
QueryWrapper<UserRole> wrapper = new QueryWrapper<>();
wrapper.eq("user_id", userRoleVo.getUserId());
userRoleDao.delete(wrapper);
// 循环添加用户的角色
for (String roleId : userRoleVo.getRoleIds()) {
UserRole userRole = new UserRole();
userRole.setUserId(userRoleVo.getUserId());
userRole.setRoleId(roleId);
userRole.setIsDeleted(0);
userRole.setGmtCreate(LocalDateTime.now());
userRole.setGmtModified(LocalDateTime.now());
// 添加用户角色信息
userRoleDao.insert(userRole);
}
return new CommonResult(2000, "添加角色成功", null);
}
}
@Data
@AllArgsConstructor
@NoArgsConstructor
@ApiModel("用户添加角色的条件对象")
public class UserRoleVo {
private String userId;
private List<String> roleIds;
}
<template>
<div>
<el-card class="box-card">
<el-breadcrumb separator-class="el-icon-arrow-right">
<el-breadcrumb-item :to="{ path: '/home' }">首页el-breadcrumb-item>
<el-breadcrumb-item>权限管理el-breadcrumb-item>
<el-breadcrumb-item>用户管理el-breadcrumb-item>
el-breadcrumb>
<el-divider>el-divider>
<el-form :inline="true" :model="userFormData" class="demo-form-inline">
<el-form-item>
<el-input v-model="userFormData.username" placeholder="请输入账号">el-input>
el-form-item>
<el-form-item>
<el-input v-model="userFormData.nickName" placeholder="请输入昵称">el-input>
el-form-item>
<el-form-item>
<el-date-picker
align="right"
type="date"
placeholder="开始日期"
v-model="userFormData.startDate"
:picker-options="startDate"
@blur="Disabled(1)"
>
el-date-picker>
el-form-item>
<el-form-item>
<el-date-picker
align="right"
type="date"
v-model="userFormData.endDate"
placeholder="结束日期"
:picker-options="endDate"
@blur="Disabled"
:disabled="isDisabled"
>
el-date-picker>
el-form-item>
<el-form-item>
<el-button type="primary" @click="onSubmit">查询el-button>
<el-button type="primary" @click="adduser">新增el-button>
el-form-item>
el-form>
<el-divider>el-divider>
<el-table
:data="tableData"
border
style="width: 100%">
<el-table-column
prop="id"
label="编号"
>
el-table-column>
<el-table-column
prop="username"
label="账户"
>
el-table-column>
<el-table-column
prop="nickName"
label="昵称">
el-table-column>
<el-table-column
prop="isDeleted"
label="状态">
<template slot-scope="scope">
<el-switch
v-model="scope.row.isDeleted"
active-color="#13ce66"
:active-value="0"
:inactive-value="1"
inactive-color="#ff4949"
@change="changeStatues(scope.row.id,scope.row.isDeleted)">
el-switch>
template>
el-table-column>
<el-table-column
prop="gmtCreate"
label="创建时间">
el-table-column>
<el-table-column
prop="gmtModified"
label="修改时间">
el-table-column>
<el-table-column label="操作" width="240">
<template slot-scope="scope">
<el-button
size="mini"
@click="handleEdit(scope.row)">编辑
el-button>
<el-button
size="mini"
type="danger"
@click="Delete(scope.row.id)">删除
el-button>
<el-button size="mini" type="warning" @click="fanPermission(scope.row.id)">分配角色el-button>
template>
el-table-column>
el-table>
<el-pagination
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
:current-page="currentPage"
:page-sizes="[4, 10, 15, 20]"
:page-size="100"
layout="total, sizes, prev, pager, next, jumper"
:total="total">
el-pagination>
el-card>
<el-dialog :title=title :visible.sync="dialogFormVisible" @closed="closeAddDialog()">
<el-form
:model="userForm"
ref="userFormref"
:rules="rules"
label-position="left"
>
<el-form-item label="用户id" hidden>
<el-input v-model="userForm.id">el-input>
el-form-item>
<el-form-item label="账户" prop="username">
<el-input v-model="userForm.username" :disabled="isDisabled">el-input>
el-form-item>
<el-form-item label="用户昵称" prop="nickName">
<el-input v-model="userForm.nickName">el-input>
el-form-item>
el-form>
<div slot="footer" class="dialog-footer">
<el-button @click="cancel">取 消el-button>
<el-button type="primary" @click="confirmAddUser()">确 定
el-button>
div>
el-dialog>
<el-dialog title="分配角色" @click="" :visible.sync="fenFormVisible">
<el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选el-checkbox>
<div style="margin: 15px 0;">div>
<el-checkbox-group v-model="checkedRoles" @change="handlecheckedRolesChange">
<el-checkbox v-for="role in roles" :label="role.id" :key="role.id">{
{role.roleName}}el-checkbox>
el-checkbox-group>
<div slot="footer" class="dialog-footer">
<el-button @click="cancel1">取 消el-button>
<el-button type="primary" @click="confirmRole">确 定
el-button>
div>
el-dialog>
div>
template>
<script>
export default {
name: "list",
data() {
return {
// value: true,
startDate: {
//禁用的情况
disabledDate(time) {
return time.getTime() > Date.now();
}
},
endDate: {
disabledDate: (time) => {
if (this.userFormData.startDate != "") {
//禁用开始日期之前的日期
return time.getTime() < new Date(this.userFormData.startDate).getTime() || time.getTime() > Date.now();
}
}
},
//表单数据对象
userFormData: {
username: '',
nickName: '',
//开始时间
startDate: '',
//结束时间
endDate: '',
},
//用来存放后台的查询的用户数据
tableData: [],
//总条数
total: 0,
//展示
currentPage: 1,
pageSize: 4,
//定义添加或者修改的标题
title: "",
//设置修改时的账户的文本框是否禁用
isDisabled: false,
change: "",
//添加框用户的对象
userForm: {
},
//控制添加的弹出框是否显示
dialogFormVisible: false,
//②添加用户的校验规则
rules: {
//表单验证
username: [
{
required: true, message: "账户不能为空", trigger: "blur"},
{
min: 3, max: 6, message: "账号的长度[3-6]", trigger: "blur"}
],
nickName: [
{
required: true, message: "昵称不能为空", trigger: "blur"}]
},
//分配角色的弹出框默认值
fenFormVisible: false,
checkAll: false,
//被选中的
checkedRoles: [],
//全部的数据
roles: [],
//定义userid
userId:"",
isIndeterminate: true
}
},
//页面初始化加载用户信息
created() {
this.selectAll();
},
methods: {
selectAll() {
var that = this;
// this.$http.post("http://localhost:8081/aaa/user/findByPage/"+this.currentPage+"/"+this.pageSize,this.userFormData).then(function (resp) {
this.$http.post(`http://localhost:8081/aaa/user/findByPage/${
this.currentPage}/${
this.pageSize}`, this.userFormData).then(function (resp) {
//所有返回的数据 axiox会封装在data属性中
//将后台查询的所有数据放到前台数组中
that.tableData = resp.data.result.records;
that.total = resp.data.result.total;
console.log(resp.data.result.records[0].isDeleted)
})
},
//开始日期没有选择,就让结束日期禁用,
Disabled(isStart) {
//isStart只有开始时间传入值,结束时间不传值,为了解决结束时间不能够赋值
if (this.userFormData.startDate === '') {
this.isDisabled = true;
} else {
//判断如果是开始时间则把结束时间清空
if (isStart == 1) {
this.isDisabled = false;
//清空结束日期的内容 为了解决先选中结束日期时候在选择开始日期,开始日期比结束日期要大
this.userFormData.endDate = ""
}
}
},
//点击查询调用查询的方法
onSubmit() {
this.selectAll();
},
//删除该用户的信息
Delete(id) {
var that = this;
//传递方式
this.$http.get("http://localhost:8081/aaa/user/deleteById", {
params: {
id: id}}).then(function (resp) {
if (resp.data.code === 2000) {
that.$message.success(resp.data.msg);
// 刷新页面
that.selectAll();
} else {
that.$message.error(resp.data.msg);
}
})
},
//点击每页的条数会发生改变
handleSizeChange(val) {
this.pageSize = val;
this.selectAll();
},
//点击当前页会发生改变
handleCurrentChange(val) {
this.currentPage = val;
this.selectAll();
},
// 状态改变的方法
changeStatues(id, isDeleted) {
var that = this;
console.log(isDeleted)
this.$http.get(`http://localhost:8081/aaa/user/updateIsDeleted/${
id}/${
isDeleted}`).then(function (resp) {
if (resp.data.code === 2000) {
that.$message.success(resp.data.msg);
} else {
that.$message.error(resp.data.msg);
}
})
},
//关闭弹出框前清空所有数据
closeAddDialog() {
this.$refs.userFormref.resetFields();
},
//添加的搜索框
adduser() {
this.dialogFormVisible = true;
this.title = "添加用户信息"
// 点击修改就将该标签禁用
this.isDisabled = false;
},
//点击编辑进行修改用户信息
handleEdit(row) {
// 打开弹出框
this.dialogFormVisible = true;
//传来当前行的所有数据
this.title = "修改用户信息";
//把当前行数据赋值给表单数据 表示深拷贝,如果直接赋值的话,就变成了浅拷贝,
// 复制的是地址,导致在表单中改变值的时候table中的数据也跟着改变,
// 所以要进行深拷贝,利用json就可以了
this.userForm = JSON.parse(JSON.stringify(row));
//这种是浅拷贝 会导致表单的值也发生改变
// this.userForm = row;
//点击修改就将该标签禁用
this.isDisabled = true;
},
//添加或修改点击确定
confirmAddUser() {
this.$refs.userFormref.validate(valid => {
if (valid) {
//如果表单验证通过,就执行添加的操作
var that = this;
this.$http.post("/aaa/user/insertOrUpdateUser", this.userForm).then(resp => {
if (resp.data.code === 2000) {
that.$message.success(resp.data.msg);
// 设置弹出层为false关闭状态 关闭弹出框
this.dialogFormVisible = false;
// 刷新表格
this.selectAll();
} else {
that.$message.error(resp.data.msg);
}
});
} else {
console.log("error submit!!");
return false;
}
});
},
//点击取消
cancel() {
this.dialogFormVisible = false;
},
cancel1() {
this.fenFormVisible = false;
},
//用户点击分配角色的按钮
fanPermission(userId) {
//开启弹出框
this.fenFormVisible = true;
this.userId=userId;
var that=this;
this.$http.get(`/aaa/role/findRoleByUserId/${
userId}`).then(function (resp) {
//把后台查到的所以权限放入roles中
that.roles=resp.data.result.allRole;
that.checkedRoles=resp.data.result.userRoleId;
})
},
//分配角色弹出框中的确认按钮
confirmRole(){
//分配角色 把被选中所有角色id传到后台,用户id
this.$http.post('/aaa/role/fenUserRole',{
userId:this.userId,roleIds:this.checkedRoles}).then(function (resp) {
//关闭弹出框
this.fenFormVisible = false;
})
},
//全选的操作
handleCheckAllChange(val) {
//先把被选中的角色Id清空
this.checkedRoles=[];
// 如果为true
if (val){
// 循环将全部的角色id放入到被选中的数组中
this.roles.forEach(item=>{
this.checkedRoles.push(item.id);
})
}
// this.checkedRoles = val ? this.roles : [];
this.isIndeterminate = false;
},
handlecheckedRolesChange(value) {
let checkedCount = value.length;
this.checkAll = checkedCount === this.roles.length;
this.isIndeterminate = checkedCount > 0 && checkedCount < this.roles.length;
}
}
}
script>
<style scoped>
style>
分配权限的前端代码
<el-dialog
title="分配权限"
:visible.sync="dialogVisible"
width="30%"
>
<el-tree
:data="data"
show-checkbox
ref="rootTree"
node-key="id"
:default-expanded-keys="checkItems"
:default-checked-keys="checkItems"
:props="defaultProps">
el-tree>
<span slot="footer" class="dialog-footer">
<el-button @click="dialogVisible = false">取 消el-button>
<el-button type="primary" @click="confirmPermission">确 定el-button>
span>
el-dialog>
data() {
return {
tableData: [],
//分配权限弹框的状态
dialogVisible: false,
//选中的 代表当前角色具有的权限id
checkItems: [],
//这里展开的就是选中的只需要用这个一个属性就行
//展开的
// expandItems:[2,3],
//所有的权限
data: [],
defaultProps: {
children: 'children',
//表示data里面的数据权限的名字 name表示后台返回权限的名字
label: 'name'
},
//角色id
roleId:"",
}
},
//点击分配权限
fanPermission(roleId) {
this.dialogVisible = true;
this.roleId=roleId;
var that = this;
//查询所有的权限 以及当前用户具有的权限id
this.$http.get("/aaa/permission/findPermissionByRoleId/" + roleId).then(function (resp) {
//默认选中的树的数据 为解决上级菜单选中子菜单也会全部选中,这里只需要上级菜单选中,子菜单可以选中一个
setTimeout(() =>{
//rootTree表示上面ref的值
resp.data.result.rolePermissionIds.forEach(value => {
//遍历角色的对应的权限Id 进行选中
that.$refs.rootTree.setChecked(value, true, false);
})}, 100)
//给所有的权限数据赋值
that.data = resp.data.result.allPermissionlist;
//勾选的参数
that.checkItems = resp.data.result.rolePermissionIds;
})
},
//点击确认按钮进行分配权限
confirmPermission() {
var that = this;
//获取全部被勾选的框的id 得到上级菜单被选中包含本身的值
var permissionIds=this.$refs.rootTree.getCheckedKeys().concat(this.$refs.rootTree.getHalfCheckedKeys())
//roldId角色id permissionIds所有权限id传到后台
this.$http.post("/aaa/permission/confirmPermission",{
roleId:this.roleId,permissionIds:permissionIds}).then(function (resp) {
that.dialogVisible = false;
})
}
methods: {
// tableRowClassName({row, rowIndex}) {
// if (rowIndex === 1) {
// return 'warning-row';
// } else if (rowIndex === 3) {
// return 'success-row';
// }
// return '';
// },
//初始化表格
initPermission() {
var that = this;
this.$http.post(`/aaa/role/findRoleByPage/1/3`).then(function (resp) {
that.tableData = resp.data.result.records;
})
},
//点击分配权限
fanPermission(roleId) {
this.dialogVisible = true;
this.roleId=roleId;
var that = this;
//查询所有的权限 以及当前用户具有的权限id
this.$http.get("/aaa/permission/findPermissionByRoleId/" + roleId).then(function (resp) {
//默认选中的树的数据 为解决上级菜单选中子菜单也会全部选中,这里只需要上级菜单选中,子菜单可以选中一个
setTimeout(() =>{
//rootTree表示上面ref的值
resp.data.result.rolePermissionIds.forEach(value => {
//遍历角色的对应的权限Id 进行选中
that.$refs.rootTree.setChecked(value, true, false);
})}, 100)
//给所有的权限数据赋值
that.data = resp.data.result.allPermissionlist;
//勾选的参数
that.checkItems = resp.data.result.rolePermissionIds;
})
},
//点击确认按钮进行分配权限
confirmPermission() {
var that = this;
//获取全部被勾选的框的id 得到上级菜单被选中包含本身的值
var permissionIds=this.$refs.rootTree.getCheckedKeys().concat(this.$refs.rootTree.getHalfCheckedKeys())
//roldId角色id permissionIds所有权限id传到后台
this.$http.post("/aaa/permission/confirmPermission",{
roleId:this.roleId,permissionIds:permissionIds}).then(function (resp) {
that.dialogVisible = false;
})
}
}
<template>
<div>
<el-card class="box-card">
<el-breadcrumb separator-class="el-icon-arrow-right">
<el-breadcrumb-item :to="{ path: '/home' }">首页el-breadcrumb-item>
<el-breadcrumb-item>权限管理el-breadcrumb-item>
<el-breadcrumb-item>角色管理el-breadcrumb-item>
el-breadcrumb>
<el-divider>el-divider>
<el-table
:data="tableData"
style="width: 100%"
>
<el-table-column
prop="id"
label="编号"
width="180">
el-table-column>
<el-table-column
prop="roleName"
label="角色名称"
width="180">
el-table-column>
<el-table-column
prop="roleCode"
label="角色编码">
el-table-column>
<el-table-column
prop="remark"
label="备注">
el-table-column>
<el-table-column
width="240"
prop="gmtCreate"
label="创建时间">
el-table-column>
<el-table-column
width="240"
prop="gmtModified"
label="创建时间">
el-table-column>
<el-table-column label="操作" width="120">
<template slot-scope="scope">
<el-button size="mini" type="success" @click="fanPermission(scope.row.id)" round>分配权限
el-button>
template>
el-table-column>
el-table>
el-card>
<el-dialog
title="分配权限"
:visible.sync="dialogVisible"
width="30%"
>
<el-tree
:data="data"
show-checkbox
ref="rootTree"
node-key="id"
:default-expanded-keys="checkItems"
:props="defaultProps">
el-tree>
<span slot="footer" class="dialog-footer">
<el-button @click="dialogVisible = false">取 消el-button>
<el-button type="primary" @click="confirmPermission">确 定el-button>
span>
el-dialog>
div>
template>
<script>
export default {
name: "list",
data() {
return {
tableData: [],
//分配权限弹框的状态
dialogVisible: false,
//选中的 代表当前角色具有的权限id
checkItems: [],
//这里展开的就是选中的只需要用这个一个属性就行
//展开的
// expandItems:[2,3],
//所有的权限
data: [],
defaultProps: {
children: 'children',
//表示data里面的数据权限的名字 name表示后台返回权限的名字
label: 'name'
},
//角色id
roleId:"",
}
},
//钩子函数
created() {
this.initPermission();
},
methods: {
// tableRowClassName({row, rowIndex}) {
// if (rowIndex === 1) {
// return 'warning-row';
// } else if (rowIndex === 3) {
// return 'success-row';
// }
// return '';
// },
//初始化表格
initPermission() {
var that = this;
this.$http.post(`/aaa/role/findRoleByPage/1/3`).then(function (resp) {
that.tableData = resp.data.result.records;
})
},
//点击分配权限
fanPermission(roleId) {
this.dialogVisible = true;
this.roleId=roleId;
var that = this;
//查询所有的权限 以及当前用户具有的权限id
this.$http.get("/aaa/permission/findPermissionByRoleId/" + roleId).then(function (resp) {
//默认选中的树的数据 为解决上级菜单选中子菜单也会全部选中,这里只需要上级菜单选中,子菜单可以选中一个
setTimeout(() =>{
//rootTree表示上面ref的值
resp.data.result.rolePermissionIds.forEach(value => {
//遍历角色的对应的权限Id 进行选中
that.$refs.rootTree.setChecked(value, true, false);
})}, 100)
//给所有的权限数据赋值
that.data = resp.data.result.allPermissionlist;
//勾选的参数
that.checkItems = resp.data.result.rolePermissionIds;
})
},
//点击确认按钮进行分配权限
confirmPermission() {
var that = this;
//获取全部被勾选的框的id 得到上级菜单被选中包含本身的值
var permissionIds=this.$refs.rootTree.getCheckedKeys().concat(this.$refs.rootTree.getHalfCheckedKeys())
//roldId角色id permissionIds所有权限id传到后台
this.$http.post("/aaa/permission/confirmPermission",{
roleId:this.roleId,permissionIds:permissionIds}).then(function (resp) {
that.dialogVisible = false;
})
}
},
}
script>
<style scoped>
.el-table .warning-row {
background: oldlace;
}
.el-table .success-row {
background: #f0f9eb;
}
style>
/**
* 根据角色id查询对应的权限id
* 查询全部的权限
* @param roldId
* @return
*/
@GetMapping("/findPermissionByRoleId/{roldId}")
public CommonResult findPermissionByRoleId(@PathVariable("roldId") String roldId) {
return permissionService.findPermissionByRoleId(roldId);
}
/**
* 点击确认分配权限
*前台传来角色id和选择的权限id
* @param rolePermissionVo
* @return
*/
@PostMapping("confirmPermission")
public CommonResult confirmPermission(@RequestBody RolePermissionVo rolePermissionVo) {
return permissionService.confirmPermission(rolePermissionVo);
}
①根据角色id查询对应的权限id
②查询全部的权限
@Override
public CommonResult findPermissionByRoleId(String roldId) {
// 查询所有的权限
List<Permission> permissions = permissionDao.selectList(null);
// 得到层级的结构
// 得到一级的菜单
List<Permission> firstPermissions = new ArrayList<>();
for (Permission permission : permissions) {
if (permission.getPid().equals("1")) {
firstPermissions.add(permission);
}
}
// 为一级菜单赋值children属性
for (Permission firstPermission : firstPermissions) {
firstPermission.setChildren(findChildren(permissions, firstPermission.getId()));
}
// 查询该角色具有的权限
QueryWrapper<RolePermission> wrapper = new QueryWrapper<>();
wrapper.eq("role_id", roldId);
List<RolePermission> rolePermissionlist = rolePermissionDao.selectList(wrapper);
// 得到permissionId列表
List<String> rolePermissionIds = rolePermissionlist.stream().map(item -> item.getPermissionId()).collect(Collectors.toList());
HashMap<String, Object> map = new HashMap<>();
map.put("allPermissionlist", firstPermissions);
map.put("rolePermissionIds", rolePermissionIds);
return new CommonResult(2000, "查询成功", map);
}
/**
* 分配权限
* @param rolePermissionVo
* @return
*/
@Transactional
@Override
public CommonResult confirmPermission(RolePermissionVo rolePermissionVo) {
// 根据roleId 删除角色权限的相关信息
QueryWrapper<RolePermission> wrapper = new QueryWrapper<>();
wrapper.eq("role_id",rolePermissionVo.getRoleId());
rolePermissionDao.delete(wrapper);
// 根据权限id 循环添加到角色权限表
for (String permissionId : rolePermissionVo.getPermissionIds()) {
RolePermission permission = new RolePermission();
permission.setGmtCreate(LocalDateTime.now());
permission.setGmtModified(LocalDateTime.now());
permission.setIsDeleted(false);
permission.setPermissionId(permissionId);
permission.setRoleId(rolePermissionVo.getRoleId());
rolePermissionDao.insert(permission);
}
return new CommonResult(2000,"添加权限成功",null);
}