尚筹网-8.Admin-Role-Auth验证

1. 权限验证

2. 给Admin分配Role

2.1 创建中间表

CREATE TABLE inner_admin_role (
    id INT (11) NOT NULL auto_increment,
    admin_id INT (11),
    role_id INT (11),
    PRIMARY KEY (id)
);

※说明:不做逆向工程,直接使用SQL操作。

2.2 思路

2.3 调整“分配”按钮

  • 所在工程:atcrowdfunding-admin-1-webui
  • 所在文件:admin-page.jsp

修改前:

<button type="button" class="btn btn-success btn-xs">
    <i class=" glyphicon glyphicon-check"></i>
</button>

修改后:

<a href="assign/to/assign/role/page.html?adminId=${admin.id }&pageNum=${requestScope['PAGE-INFO'].pageNum}" class="btn btn-success btn-xs">
    <i class=" glyphicon glyphicon-check"></i>
</a>

2.4 创建AssignHandler

@Controller
public class AssignHandler {    
    @Autowired
    private RoleService roleService;
    @RequestMapping("/assign/to/assign/role/page")
    public String toAssignRolePage(@RequestParam("adminId") Integer adminId, Model model) {
        // 1.查询已分配角色
        List<Role> assignedRoleList = roleService.getAssignedRoleList(adminId);
        // 2.查询未分配角色
        List<Role> unAssignedRoleList = roleService.getUnAssignedRoleList(adminId);
        // 3.存入模型
        model.addAttribute("assignedRoleList", assignedRoleList);
        model.addAttribute("unAssignedRoleList", unAssignedRoleList);   
        return "assign-role";
    }
}

2.5 查询已分配、未分配角色的SQL

<select id="selectAssignedRoleList" resultMap="BaseResultMap">
    SELECT
        r.id,
        r.`name`
    FROM
        t_role r
    LEFT JOIN inner_admin_role ar ON r.id = ar.role_id
    WHERE
        ar.admin_id = #{adminId}
</select>
<select id="selectUnAssignedRoleList" resultMap="BaseResultMap">
    SELECT
        id,
        `name`
    FROM
        t_role
    WHERE
        id NOT IN (
            SELECT
                role_id
            FROM
                inner_admin_role
            WHERE
                admin_id = #{adminId}
        )
</select>

2.6 创建assign-role.jsp

/atcrowdfunding-admin-1-webui/src/main/webapp/WEB-INF/assign-role.jsp

表单内容

<form action="assign/role.html" method="post" role="form"
      class="form-inline">
    <input type="hidden" name="adminId" value="${param.adminId }"/>
    <input type="hidden" name="pageNum" value="${param.pageNum }"/>
    <div class="form-group">
        <label for="exampleInputPassword1">未分配角色列表</label><br>
        <select
                id="leftSelect" class="form-control" multiple size="10"
                style="width: 100px; overflow-y: auto;">
            <c:forEach items="${requestScope.unAssignedRoleList }" var="role">
                <option value="${role.id }">${role.name }</option>
            </c:forEach>
        </select>
    </div>
    <div class="form-group">
        <ul>
            <li id="rightBtn"
                class="btn btn-default glyphicon glyphicon-chevron-right"></li>
            <br>
            <li id="leftBtn"
                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
                id="rightSelect" name="roleIdList" class="form-control"
                multiple size="10" style="width: 100px; overflow-y: auto;">
            <c:forEach items="${requestScope.assignedRoleList }" var="role">
                <option value="${role.id }">${role.name }</option>
            </c:forEach>
        </select>
    </div>
    <button id="submitBtn" type="submit" style="width: 200px;"
            class="btn btn-success btn-lg btn-block">分配
    </button>
</form>

2.7 左右移动option

$("#rightBtn").click(function(){
    $("#leftSelect>option:selected").appendTo("#rightSelect");
});
$("#leftBtn").click(function(){
    $("#rightSelect>option:selected").appendTo("#leftSelect");
});

2.8 执行分配的handler方法

@RequestMapping("/assign/role")
public String doAssignRole(
    // roleIdList不一定每一次都能够提供,没有提供我们也接受
    @RequestParam(value="roleIdList", required=false) List<Integer> roleIdList, 
    @RequestParam("adminId") Integer adminId,
    @RequestParam("pageNum") String pageNum) {  
    roleService.updateRelationship(adminId, roleIdList);    
    return "redirect:/admin/query/for/search.html?pageNum="+pageNum;
}

2.9 执行分配的service方法

@Override
public void updateRelationship(Integer adminId, List<Integer> roleIdList) {
    // 1.删除全部旧数据
    roleMapper.deleteOldAdminRelationship(adminId);
    // 2.保存全部新数据
    if(CrowdFundingUtils.collectionEffective(roleIdList)) {
        roleMapper.insertNewAdminRelationship(adminId, roleIdList);
    }   
}

2.10 执行分配的SQL

<delete id="deleteOldAdminRelationship">
    delete from inner_admin_role where admin_id=#{adminId}
</delete>
<insert id="insertNewAdminRelationship">
    insert into inner_admin_role(admin_id,role_id)
    values
    <foreach collection="roleIdList" item="roleId" separator=",">(#{adminId},#{roleId})</foreach>
</insert>

2.11 填坑

  • 问题描述:默认情况下,表单只提交select中选中的option。
  • 问题解决:在表单提交前把select中所有option全部选中
$("#submitBtn").click(function(){
    $("#rightSelect>option").prop("selected","selected");
});

3. 创建权限模型

3.1 建表

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`)
);

3.2 字段说明

  • id:主键

  • name:实际权限信息。

    • user:add

    • user:delete

    • role:delete

    • role:get

    • ……

      ※这里使用的“:”没有任何语法层面的要求,仅仅是表示“模块:操作”含义。

  • title:页面显示信息

  • category_id:权限分类id。这个字段关联本表中的其他记录的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);

3.3 inner_role_auth中间表

CREATE TABLE `inner_role_auth` (
  `role_id` int(11) DEFAULT NULL,
  `auth_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`role_id`,`auth_id`)
);

3.4 逆向工程

<table tableName="t_auth" domainObjectName="Auth" />

4. 角色分配权限

4.1 后端查询全部权限数据

handler:

@ResponseBody
@RequestMapping("/assign/get/all/auth")
public ResultEntity<List<Auth>> getAllAuth() {
    List<Auth> authList = authService.getAllAuth(); 
    return ResultEntity.successWithData(authList);
}

service:

@Override
public List<Auth> getAllAuth() {
    return authMapper.selectByExample(new AuthExample());
}

4.2 准备模态框页面

/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">&times;</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>
<%@ include file="/WEB-INF/include-modal-assign-auth.jsp" %>

4.3 给分配按钮绑定单击响应函数

/atcrowdfunding-admin-1-webui/src/main/webapp/script/my-role.js

function generateTableBody(pageInfo) {
    ……
    for(var i = 0; i < list.length; i++) {
        ……
        var checkBtn = "<button roleId='"+role.id+"' type='button' class='btn btn-success btn-xs checkBtn'>……</button>";
        ……

role-page.jsp

$("#roleTableBody").on("click",".checkBtn",function(){
    // 将角色id存入全局变量
    window.roleId = $(this).attr("roleId");
    $("#roleAssignAuthModal").modal("show");
});

4.4 在模态框中显示树形结构

4.4.1 导入zTree环境

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中的代码。

4.4.2 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
    }
};

4.4.3 获取JSON数据并显示树形结构

$("#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);   
});

4.5 回显已分配权限

4.5.1 获取以前分配过的权限信息

后端代码

handler

@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);
}

service

@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(){}函数内

// 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;

4.5.2 根据以前分配的信息勾选树形节点

// 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不应该勾选,这就会产生错误。

4.6 执行分配

4.6.1前端代码

// 给在模态框中的分配按钮绑定单击响应函数
$("#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");
});

4.6.2 后端代码

handler

@ResponseBody
@RequestMapping("/assign/do/assign")
public ResultEntity<String> daRoleAssignAuth(@RequestBody Map<String,List<Integer>> assignDataMap){
    authService.updateRelationShipBetweenRoleAndAuth(assignDataMap);
    return ResultEntity.successWithoutData();
}

service

@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);
    }
}

SQL

<delete id="deleteOldRelationship">
    delete from inner_role_auth where role_id=#{roleId}
</delete>
<insert id="insertNewRelationship">
    insert into inner_role_auth(role_id,auth_id)
    values
    <foreach collection="authIdList" item="authId" separator=",">(#{roleId},#{authId})</foreach>
</insert>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容