准备
建权限表
CREATE TABLE `t_auth` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(200) DEFAULT NULL,
`title` varchar(200) DEFAULT NULL,
`category_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
);
INSERT INTO t_auth(id,`name`,title,category_id) VALUES(1,'','用户模块',NULL);
INSERT INTO t_auth(id,`name`,title,category_id) VALUES(2,'user:delete','删除',1);
INSERT INTO t_auth(id,`name`,title,category_id) VALUES(3,'user:get','查询',1);
INSERT INTO t_auth(id,`name`,title,category_id) VALUES(4,'','角色模块',NULL);
INSERT INTO t_auth(id,`name`,title,category_id) VALUES(5,'role:delete','删除',4);
INSERT INTO t_auth(id,`name`,title,category_id) VALUES(6,'role:get','查询',4);
INSERT INTO t_auth(id,`name`,title,category_id) VALUES(7,'role:add','新增',4);
权限表字段说明
- id:主键
- name:实际权限信息。
- user:add
- user:delete
- role:delete
- role:get
……
※这里使用的“:”没有任何语法层面的要求,仅仅是表示“模块:操作”含义。
- title:页面显示信息
- category_id:权限分类id。这个字段关联本表中的其他记录的id字段,已便于使用树形结构显示权限数据。
页面上对应的显示效果如下所示:
inner_role_auth中间表
CREATE TABLE `inner_role_auth` (
`role_id` int(11) ,
`auth_id` int(11) ,
PRIMARY KEY (`role_id`,`auth_id`)
);
逆向工程
0、
<table tableName="t_auth" domainObjectName="Auth" />
1、选择pom.xml----》 Run as —》 Maven build … —》将Goal的值设置为:mybatis-generator:generate----》Run,然后刷新
2、Auth.java添加有参,无参构造函数以及toString函数
3、逆向资源各就各位
角色分配权限
查询全部权限数据【后端】
1、/atcrowdfunding-admin-2-component/src/main/java/com/atguigu/crowd/funding/handler/AuthHandler.java
@Controller
public class AuthHandler {
@Autowired
private AuthService authService;
@ResponseBody
@RequestMapping("/assign/get/all/auth")
public ResultEntity<List<Auth>> getAllAuth() {
List<Auth> authList = authService.getAllAuth();
return ResultEntity.successWithData(authList);
}
}
2、/atcrowdfunding-admin-2-component/src/main/java/com/atguigu/crowd/funding/service/impl/AuthServiceImpl.java
@Service
public class AuthServiceImpl implements AuthService{
@Autowired
private AuthMapper authMapper;
@Override
public List<Auth> getAllAuth() {
return authMapper.selectByExample(new AuthExample());
}
}
3、http://localhost:8080/atcrowdfunding-admin-1-webui/assign/get/all/auth.json
准备模态框页面
1、/atcrowdfunding-admin-1-webui/src/main/webapp/WEB-INF/include-modal-assign-auth.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<div id="roleAssignAuthModal" class="modal fade" tabindex="-1" role="dialog">
<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">尚筹网系统弹窗</h4>
</div>
<div class="modal-body">
<ul id="treeDemo" class="ztree"></ul>
</div>
<div class="modal-footer">
<button id="roleAssignAuthBtn" type="button" class="btn btn-primary">分配</button>
</div>
</div>
</div>
</div>
2、/atcrowdfunding-admin-1-webui/src/main/webapp/WEB-INF/role-page.jsp最下面的body标签的上面引用
<%@ include file="/WEB-INF/include-modal-assign-auth.jsp" %>
</body>
给分配按钮绑定单击响应函数
1、/atcrowdfunding-admin-1-webui/src/main/webapp/script/my-role.js
var checkBtn = "<button roleId='"+role.id+"' type='button' class='btn btn-success btn-xs checkBtn'><i class=' glyphicon glyphicon-check'></i></button>";
2、/atcrowdfunding-admin-1-webui/src/main/webapp/WEB-INF/role-page.jsp
$("#roleTableBody").on("click",".checkBtn",function(){
// 将角色id存入全局变量
window.roleId = $(this).attr("roleId");
$("#roleAssignAuthModal").modal("show");
});
3、运行测试:点击权限管理—角色维护----编辑,跳出模态框了
在模态框中显示树形结构
导入zTree环境
/atcrowdfunding-admin-1-webui/src/main/webapp/WEB-INF/role-page.jsp
<link rel="stylesheet" href="ztree/zTreeStyle.css" />
<script type="text/javascript" src="ztree/jquery.ztree.all-3.5.min.js"></script>
zTree一定要在jQuery后面引入。如果A.js中用到了B.js里面的代码,那么B必须在A前面引入,否则A无法使用B中的代码。
zTree设置
- 启用简单JSON功能
setting.data.simpleData.enable设置为true - 设置显示节点名称的实体类属性名
setting.data.key.name设置为title - 设置当前节点父节点的属性名
setting.data.simpleData.pIdKey设置为categoryId - 展开整个树形结构
$.fn.zTree.getZTreeObj(“treeDemo”).expandAll(true); - 设置树形节点前显示checkbox
setting.check.enable设置为true
var setting = {
"data": {
"simpleData": {
"enable": true,
"pIdKey": "categoryId"
},
"key": {
"name": "title"
}
},
"check": {
"enable": true
}
};
获取JSON数据并显示树形结构
/atcrowdfunding-admin-1-webui/src/main/webapp/WEB-INF/role-page.jsp
$("#roleTableBody").on("click",".checkBtn",function(){
// 打开模态框
$("#roleAssignAuthModal").modal("show");
// 初始化模态框中显示的树形结构
// 1.创建setting对象
var setting = {
"data": {
"simpleData": {
"enable": true,
"pIdKey": "categoryId"
},
"key": {
"name": "title"
}
},
"check": {
"enable": true
}
};
// 2.获取JSON数据
var ajaxResult = $.ajax({
"url": "assign/get/all/auth.json",
"type": "post",
"dataType": "json",
"async": false
});
if(ajaxResult.responseJSON.result == "FAILED") {
layer.msg(ajaxResult.responseJSON.message);
return ;
}
var zNodes = ajaxResult.responseJSON.data;
// 3.初始化树形结构
$.fn.zTree.init($("#treeDemo"), setting, zNodes);
});
测试
回显已分配权限
获取以前分配过的权限信息
后端
@ResponseBody
@RequestMapping("/assign/get/assigned/auth/id/list")
public ResultEntity<List<Integer>> getAssignedAuthIdList(@RequestParam("roleId") Integer roleId) {
List<Integer> authIdList = authService.getAssignedAuthIdList(roleId);
return ResultEntity.successWithData(authIdList);
}
@Override
public List<Integer> getAssignedAuthIdList(Integer roleId) {
return authMapper.selectAssignedAuthIdList(roleId);
}
<select id="selectAssignedAuthIdList" resultType="int">
select auth_id from inner_role_auth where role_id=#{roleId}
</select>
前端
$("#roleTableBody").on("click",".checkBtn",function(){
// 将角色id存入全局变量
window.roleId = $(this).attr("roleId");
$("#roleAssignAuthModal").modal("show");
// 1.创建setting对象
var setting = {
"data": {
"simpleData": {
"enable": true,
"pIdKey": "categoryId"
},
"key": {
"name": "title"
}
},
"check": {
"enable": true
}
};
// 2.获取JSON数据
var ajaxResult = $.ajax({
"url": "assign/get/all/auth.json",
"type": "post",
"dataType": "json",
"async": false
});
if(ajaxResult.responseJSON.result == "FAILED") {
layer.msg(ajaxResult.responseJSON.message);
return ;
}
var zNodes = ajaxResult.responseJSON.data;
// 3.初始化树形结构
$.fn.zTree.init($("#treeDemo"), setting, zNodes);
// 4.将树形结构展开
$.fn.zTree.getZTreeObj("treeDemo").expandAll(true);
// 5.查询以前已经分配过的authId
ajaxResult = $.ajax({
"url": "assign/get/assigned/auth/id/list.json",
"type": "post",
"data": {
"roleId": $(this).attr("roleId"),
"random": Math.random()
},
"dataType": "json",
"async": false
});
if(ajaxResult.responseJSON.result == "FAILED") {
layer.msg(ajaxResult.responseJSON.message);
return ;
}
var authIdList = ajaxResult.responseJSON.data;
// 6.使用authIdList勾选对应的树形节点
// ①遍历authIdList
for (var i = 0; i < authIdList.length; i++) {
// ②在遍历过程中获取每一个authId
var authId = authIdList[i];
// ③根据authId查询到一个具体的树形节点
// key:查询节点的属性名
// value:查询节点的属性值,这里使用authId
var key = "id";
var treeNode = $.fn.zTree.getZTreeObj("treeDemo").getNodeByParam(key, authId);
// ④勾选找到的节点
// treeNode:当前要勾选的节点
// true:表示设置为勾选状态
// false:表示不联动
$.fn.zTree.getZTreeObj("treeDemo").checkNode(treeNode, true, false);
}
});
※为什么不能联动:在联动模式下,子菜单A勾选会导致父菜单勾选,父菜单勾选会根据“联动”效果,把子菜单B、子菜单C也勾选,可是实际上B、C不应该勾选,这就会产生错误。
执行分配【系统出现未知错误,待解决】
前端
/atcrowdfunding-admin-1-webui/src/main/webapp/WEB-INF/role-page.jsp
// 给在模态框中的分配按钮绑定单击响应函数
$("#roleAssignAuthBtn").click(function(){
var authIdArray = new Array();
// 调用zTreeObj的方法获取当前已经被勾选的节点
var checkedNodes = $.fn.zTree.getZTreeObj("treeDemo").getCheckedNodes();
// 遍历checkedNodes
for(var i = 0; i < checkedNodes.length; i++) {
// 获取具体的一个节点
var node = checkedNodes[i];
// 获取当前节点的id属性
var authId = node.id;
// 将authId存入数组
authIdArray.push(authId);
}
// 在handler方法中使用@RequestBody接收
// 方便使用的数据类型是:@RequestBody Map<String, List<Integer>>
// {"roleIdList":[2],"authIdList":[2,3,5,7]}
// 封装要发送给handler的JSON数据
var requestBody = {"roleIdList":[window.roleId], "authIdList": authIdArray};
// 发送请求
var ajaxResult = $.ajax({
"url": "assign/do/assign.json",
"type": "post",
"data": JSON.stringify(requestBody),
"contentType": "application/json;charset=UTF-8",
"dataType": "json",
"async": false
});
if(ajaxResult.responseJSON.result == "SUCCESS") {
layer.msg("操作成功!");
}
if(ajaxResult.responseJSON.result == "FAILED") {
layer.msg(ajaxResult.responseJSON.message);
}
$("#roleAssignAuthModal").modal("hide");
});
后端
@ResponseBody
@RequestMapping("/assign/do/assign")
public ResultEntity<String> doRoleAssignAuth(
@RequestBody Map<String, List<Integer>> assignDataMap) {
authService.updateRelationShipBetweenRoleAndAuth(assignDataMap);
return ResultEntity.successWithoutData();
}
@Override
public void updateRelationShipBetweenRoleAndAuth(Map<String, List<Integer>> assignDataMap) {
// 1.获取两部分List数据
List<Integer> roleIdList = assignDataMap.get("roleIdList");
List<Integer> authIdList = assignDataMap.get("authIdList");
// 2.取出roleId
Integer roleId = roleIdList.get(0);
// 3.删除旧数据
authMapper.deleteOldRelationship(roleId);
// 4.保存新数据
if(CrowdFundingUtils.collectionEffective(authIdList)) {
authMapper.insertNewRelationship(roleId, authIdList);
}
}