1、用户分配角色
效果图:
实现思路:
1)先静态实现页面
2)从数据库查询用户未分配角色和已分配角色,前端初始化该列表
3)添加、移除用户拥有的角色
前端:
1)左移、右移:append和appendTo的使用
$(".unroles :selected").appendTo(".roles_select")
2)遍历选中的角色
//遍历选中的元素,拼接用户角色id
$('.unroles :selected').each(function() {
log(this)
rids += $(this).val() + ','
})
3)ajax发送异步请求(参数拼接:用户id,角色rids)
uid = '${param.uid}'
url = '${ctp}/permission/user/assignrole?opt=remove&uid='
+ uid + '&rids=' + rids + ''
//发送请求移除
$.get(url, fnf)
<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)
// 添加移除用户角色
@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个表多表查询
<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自定义图标显示不出来
<!-- 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">×</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>
控制层:
//分配权限
@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;
}
业务层:
// 更新权限树
@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;
}