用户分配角色_角色维护权限树

1、用户分配角色

效果图:

实现思路:

1)先静态实现页面

2)从数据库查询用户未分配角色和已分配角色,前端初始化该列表

3)添加、移除用户拥有的角色

前端:

1)左移、右移:append和appendTo的使用

1
2

$(".unroles :selected").appendTo(".roles_select")

2)遍历选中的角色

1
2
3
4
5
6

//遍历选中的元素,拼接用户角色id
$('.unroles :selected').each(function() {
log(this)
rids += $(this).val() + ','
})

3)ajax发送异步请求(参数拼接:用户id,角色rids)

1
2
3
4
5
6
7

uid = '${param.uid}'
url = '${ctp}/permission/user/assignrole?opt=remove&uid='
+ uid + '&rids=' + rids + ''

//发送请求移除
$.get(url, fnf)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121

<div class="panel panel-default">
<div class="panel-body">
<form role="form" class="form-inline">
<div class="form-group">
<label for="exampleInputPassword1">未分配角色列表</label><br> <select
class="form-control unroles" multiple size="10"
style="width: 100px; overflow-y: auto;">
<c:forEach items="${list_user_unrole}" var="user_unrole">
<option value="${user_unrole.id}">${user_unrole.name}</option>
</c:forEach>
</select>
</div>
<div class="form-group">
<ul>
<li class="btn btn-default glyphicon glyphicon-chevron-right"></li>
<br>
<li class="btn btn-default glyphicon glyphicon-chevron-left"
style="margin-top: 20px;"></li>
</ul>
</div>
<div class="form-group" style="margin-left: 40px;">
<label for="exampleInputPassword1">已分配角色列表</label><br> <select
class="form-control roles_select" multiple size="10"
style="width: 100px; overflow-y: auto;">
<c:forEach items="${list_user_role}" var="user_role">
<option value="${user_role.id}">${user_role.name}</option>
</c:forEach>
</select>
</div>
</form>
</div>
</div>





<script type="text/javascript">
$(function() {
$(".list-group-item").click(function() {
if ($(this).find("ul")) {
$(this).toggleClass("tree-closed");
if ($(this).hasClass("tree-closed")) {
$("ul", this).hide("fast");
} else {
$("ul", this).show("fast");
}
}
});
});

//页面加载完成执行
$(function() {
addUserRoleEvent()
removeUserRoleEvent()
})

//用户添加角色事件
var addUserRoleEvent = function() {
$('.glyphicon-chevron-right').click(
function() {
log('向右移动=============>')
var uid = ''
var rids = ''
//遍历选中的元素,拼接用户角色id
$('.unroles :selected').each(function() {
log(this)
rids += $(this).val() + ','
})
rids = rids.substring(0, rids.length - 1)
log('用户角色ids==========>', rids)

uid = '${param.uid}'
url = '${ctp}/permission/user/assignrole?opt=add&uid='
+ uid + '&rids=' + rids + ''

//选中的得进行处理添加到用户角色表中
//发送请求给当前用户添加这几个角色,必须带上权限id的拼串和userid
$.get(url, fns)

})
}

//用户删除角色事件
var removeUserRoleEvent = function() {
$('.glyphicon-chevron-left')
.click(
function() {
log('向左移动=============>')
var rids = ''
$('.roles_select :selected').each(function() {
rids += $(this).val() + ','
})
rids = rids.substring(0, rids.length - 1)
log('用户角色ids==========>', rids)

uid = '${param.uid}'
url = '${ctp}/permission/user/assignrole?opt=remove&uid='
+ uid + '&rids=' + rids + ''

//发送请求移除
$.get(url, fnf)
})
}

//异步请求成功的回调函数
var fns = function(data) {
log('异步请求成功的回调函数===============>')
log('data===========>', data)
//$('.roles_select').append($('.unroles :selected'))
$(".unroles :selected").appendTo(".roles_select")

}
//异步请求失败的回调函数
var fnf = function(data) {
log('异步请求失败的回调函数===============>')
log('data===========>', data)
$('.roles_select :selected').appendTo('.unroles')
}
</script>

控制层:

1)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54


// 添加移除用户角色
@RequestMapping("/assignrole")
@ResponseBody
public String userRole(@RequestParam("uid") Integer uid, @RequestParam("rids") String rids,
@RequestParam("opt") String opt) {
System.out.println("添加移除用户角色==================>");
System.out.println("用户id-----角色ids------类型:添加、移除");
System.out.println(uid);
System.out.println(rids);
System.out.println(opt);

if ("add".equals(opt)) {
// 为某个用户添加角色
int i = userRoleService.add(uid, rids);

} else if ("remove".equals(opt)) {
// 为某个用户删除角色
int i = userRoleService.remove(uid, rids);
}

return "success";
}

@RequestMapping("/toAssignRolePage")
public String toAssignRolePage(@RequestParam(value = "uid") Integer uid, Model model) {
System.out.println("UserController.toAssignRolePage去分配角色页面=============>");
// 1、查出所有角色
List<TRole> list_role = roleService.getAllRole();
System.out.println("所有角色===========>");
System.out.println(list_role);
// 2、查出当前用户拥有的角色
List<TRole> list_user_role = roleService.getUserRole(uid);
System.out.println("当前用户的角色==========>");
System.out.println(list_user_role);
HashMap<Integer, TRole> map_user_role = new HashMap<>();
for (TRole tRole : list_user_role) {
map_user_role.put(tRole.getId(), tRole);
}
// 3、用户未分配的角色
ArrayList<TRole> list_user_unrole = new ArrayList<>();
for (TRole tRole : list_role) {
if (!map_user_role.containsKey(tRole.getId())) {
list_user_unrole.add(tRole);
}
}
System.out.println("用户未分配的角色=============>");
System.out.println(list_user_unrole);
model.addAttribute("list_user_role", list_user_role);
model.addAttribute("list_user_unrole", list_user_unrole);
// model.addAttribute("uid", uid);
return "manager/permission/assignRole";
}

sql:

1)用户表、用户_角色表、角色表3个表多表查询

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

<resultMap id="BaseResultMap"
type="com.atguigu.scw.manager.bean.TRole">
<id column="id" jdbcType="INTEGER" property="id" />
<result column="name" jdbcType="VARCHAR" property="name" />
</resultMap>

<!-- List<TRole> getUserRole(Integer uid); -->
<select id="getUserRole" resultMap="BaseResultMap">
SELECT
a.*
FROM
t_role a
LEFT JOIN t_user_role b
ON a.`id` = b.`roleid`
LEFT JOIN t_user c
ON b.`userid` = c.`id`
WHERE c.`id` = #{uid}
</select>

2、角色维护权限树

效果图:

实现思路:

1)zTree展示权限树,初始化含有复选框的权限树,异步请求控制层(参数:角色rid)查询出角色拥有的权限

2)点击分配权限携带角色rid和权限permission_ids到控制层,先删除角色所拥有的权限,再更加permission_ids更新角色拥有的权限,同步到前端

3)bootstrap模态框–分配权限按钮绑定参数

前端:

1)zTree权限树复选框初始化的时候刚开始使用2次异步请求(一次请求所有权限,一次请求角色拥有的权限),展示数据有点混乱,后来改为一次异步请求同时查询出(所有权限、角色拥有的权限)。

2)bootstrap自定义图标显示不出来

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201

<!-- Modal模态框 -->
<div class="modal fade" id="permissModel" tabindex="-1" role="dialog"
aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"
aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
<!--展示权限树 -->
<ul id="permissionTree" class="ztree"></ul>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
<button type="button" class="btn btn-primary" id='addPermissionBtn'>分配权限</button>
</div>
</div>
</div>
</div>

<script type="text/javascript">
$(function() {
$(".list-group-item").click(function() {
if ($(this).find("ul")) {
$(this).toggleClass("tree-closed");
if ($(this).hasClass("tree-closed")) {
$("ul", this).hide("fast");
} else {
$("ul", this).show("fast");
}
}
});
});

/* $("tbody .btn-success").click(function() {
window.location.href = "assignPermission.html";
}); */

var zTree

//设置ajax同步
//$.ajaxSettings.async = false
var assignPermissionEvent = function() {
$(".assignPermissionModelBtn").click(function() {
log('assignPermissionEvent==============>')
//获取当前角色id
log('当前角色id==========>', $(this).attr('rid'))
var rid = $(this).attr('rid')
loadModalAndTree(rid)

})
}

var loadModalAndTree = function(rid) {
//模态框设置
var options = {
backdrop : 'static',
show : true
}
//手动打开模态框
$('#permissModel').modal(options)

//从数据库查出的所有权限节点数据
//发送ajax请求获取到所有权限的json数据
var url = '${ctp}/permission/role/json/' + rid
$.getJSON(url, fns)

//将角色id保存到模态框的哪个属性中;
//打开模态框将角色id传递给model里面的权限分配按钮
log('角色id===========>', rid)
$('#addPermissionBtn').attr("rid", rid)
}

//成功回调函数,刷新权限树
var fns = function(data) {
log('成功返回数据', data)
log('event==========>', event)

var ids = []
$.each(data.listCurrentPermission, function() {
ids.push(this.id)
})
log('ids===========>', ids)
//遍历每一条权限
$.each(data.listPermission, function() {
//给每一个节点修改或者添加一些属性
if (this.pid == 0) {
this.open = true
}
if (ids.includes(this.id)) {
this.checked = true
}
})

var setting = {
data : {
simpleData : {
enable : true,
idKey : "id",
pIdKey : "pid",
},
key : {
url : "haha"
}

},
/* view : {
addDiyDom : showIcon
}, */
check : {
enable : true
}
}

zTree = $.fn.zTree.init($("#permissionTree"), setting,
data.listPermission)
log('zTree赋值完成==========>', zTree)

}

//用于在节点上固定显示用户自定义控件
//?图标无法正常显示可能是字体样式没有引入进来
var showIcon = function(treeId, treeNode) {
log('自定义显示图标==============>')
log('treeId===============>', treeId)
log('treeNode===============>', treeNode)
//#permissionTree_10_ico
$("#" + treeNode.tId + "_ico").removeClass()
.addClass(treeNode.icon)

}

//默认勾选当前角色的权限
var checkcurPermisson = function(rid) {
var url = '${ctp}/permission/role/curPermission/' + rid
$.getJSON(url, fns2)
}

//获取当前角色权限成功回调函数
var fns2 = function(data) {
log('fns2===============>')
log('fns2_data================', data)

//遍历当前角色拥有的权限
$.each(data, function() {
//$(this).attr('id')
var node = zTree.getNodesByParam('id', this.id, null)
log('使用zTree===========>', zTree)
log('当前角色拥有的权限=============>', node)
zTree.checkNode(node, true, false)
log('是否选中=========>', node.checked)
node.nocheck = true //表示显示checkbox
})

}

//更新权限树
var updateTree = function() {
log('更新权限树===========>')
var rid = $('#addPermissionBtn').attr("rid")
log('角色rid==========>', rid)
var permission_ids = ''
//1、获取当前我们已经选中的权限
var nodes = zTree.getCheckedNodes(true)
log('nodes=============>', nodes)
$.each(nodes, function() {
permission_ids += this.id + ','
})
var url = '${ctp}/permission/role/update?rid=' + rid
+ '&permission_ids=' + permission_ids
$.get(url, updateTreeFn)

}
//更新权限树回调函数
var updateTreeFn = function(data) {
alert(data)
log("权限分配成功===========>");
$('#permissModel').modal("hide");
}

var addPermissionBtnEvent = function() {
$('#addPermissionBtn').click(function() {
log('点击分配权限按钮=============>')
updateTree()
})
}

var __main = function() {
assignPermissionEvent()
addPermissionBtnEvent()
}

$(function() {
__main()
})
</script>

控制层:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36

//分配权限
@RequestMapping("/update")
@ResponseBody
public String updateRolePermission(@RequestParam("rid") Integer rid,
@RequestParam("permission_ids") String permission_ids) {
System.out.println("更新权限==========>");
System.out.println(rid);
System.out.println(permission_ids);
// 先删除该角色所有权限,在为该用户分配权限
boolean flag = rolePermissionService.updatePermission(rid, permission_ids);

return flag ? "success" : "fail";
}

@RequestMapping("/curPermission/{id}")
@ResponseBody
public List<TPermission> getCurrentPermission(@PathVariable("id") Integer rid) {
System.out.println("当前角色拥有的权限==============>");
List<TPermission> listPermission = permissionService.getPermissionsById(rid);
System.out.println(listPermission);
return listPermission;
}

//查出角色拥有的权限、所有权限
@RequestMapping("/json/{id}")
@ResponseBody
public HashMap<String, List<TPermission>> getAllPermission(@PathVariable("id") Integer rid) {

List<TPermission> listPermission = permissionService.getPermissions();
List<TPermission> listCurrentPermission = permissionService.getPermissionsById(rid);
HashMap<String, List<TPermission>> map = new HashMap<>();
map.put("listPermission", listPermission);
map.put("listCurrentPermission", listCurrentPermission);
return map;
}

业务层:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52

// 更新权限树
@Override
public boolean updatePermission(Integer rid, String permission_ids) {
// 删除角色权限
TRolePermissionExample tRolePermissionExample = new TRolePermissionExample();
Criteria criteria = tRolePermissionExample.createCriteria();
criteria.andRoleidEqualTo(rid);
int count = mapper.deleteByExample(tRolePermissionExample);

// 更新权限
if (permission_ids.contains(",")) {
String[] split = permission_ids.split(",");
for (String permission_id : split) {
int i = Integer.parseInt(permission_id);
TRolePermission rolePermission = new TRolePermission();
// 设置权限id
rolePermission.setPermissionid(i);
// 设置角色id
rolePermission.setRoleid(rid);
// 保存角色权限关系
mapper.insertSelective(rolePermission);
}

} else {
int i = Integer.parseInt(permission_ids);
TRolePermission rolePermission = new TRolePermission();
// 设置权限id
rolePermission.setPermissionid(i);
// 设置角色id
rolePermission.setRoleid(rid);
// 保存角色权限关系
mapper.insertSelective(rolePermission);

}
return true;
}


// 为角色分配权限,查询所有权限
@Override
public List<TPermission> getPermissions() {

List<TPermission> list_permission = mapper.selectByExample(null);
return list_permission;
}

@Override
public List<TPermission> getPermissionsById(Integer rid) {
List<TPermission> list_permission = mapper.getRolePermission(rid);
return list_permission;
}