码迷,mamicode.com
首页 > 编程语言 > 详细

JavaEE权限管理系统的搭建(八)--------角色的增删改

时间:2019-02-02 23:38:28      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:调试   初始   end   dde   fun   循环   var   登录   加载   

 

如下图所示,添加角色的同时,要给角色分配权限菜单,关于权限数的显示,我实现了两种方式,普通方式和Ztree方式,

 

普通方式展示树:

 

技术图片

 

主要代码部分:

 

/**
     * 进入角色添加页面
     * @param model
     * @return
     */
    @AccessPermissionsInfo("role:add")
    @RequestMapping(value = "/role-add.action",method = RequestMethod.GET)
    public String roleAddPage(Model model){

        Role role = new Role();
        model.addAttribute("role",role);

        //获取所有权限集合
        List<Permission> allPermissionsList =
                permissionService.findAllPermission();

        //储存的是根节点集合
        List<Permission> permissionsList = new ArrayList<Permission>();
        //获取所有根节点
        for(Permission p:allPermissionsList){
            if(p.getParentId().toString().equals("0")||
                    Integer.parseInt(p.getParentId().toString())==0){
                permissionsList.add(p);
            }
        }

        //遍历根节点集合,为根节点设置子节点
        for(Permission p:permissionsList){
            //findChild方法递归查找子节点
            p.setChildPermissions(findChild(p.getId(),allPermissionsList));
        }

        model.addAttribute("permissionsList",permissionsList);

        return "role-add";
    }


    /**
     * 查找子节点
     * @param id 父节点的ID
     * @param allPermissionsList 所有权限的集合
     * @return
     */
    private List<Permission> findChild(Integer id,
                                       List<Permission> allPermissionsList) {

        List<Permission> childPermissions = new ArrayList<Permission>();
        //遍历所有权限列表
        for(Permission p:allPermissionsList){
            //如果子节点的parentId等于父节点的ID
            if(p.getParentId().equals(id)){
                //添加到子节点
                childPermissions.add(p);
            }
        }

        //再次循环子菜单
        for(Permission p:childPermissions){
            p.setChildPermissions(findChild(p.getId(),allPermissionsList));
        }


        if(childPermissions.size()==0){
            return null;
        }

        return childPermissions;

    }


    /**
     * 添加角色信息
     * @param request
     * @return
     */
    @AccessPermissionsInfo("role:add")
    @RequestMapping(value = "/role-add.action",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> roleAdd(HttpServletRequest request)
    {
        Map<String,Object> resultMap = new HashMap<String,Object>();

        String[] ids = request.getParameterValues("pers");

        if(request.getParameter("roleName")==null||
                request.getParameter("roleRemark")==null)
        {
            resultMap.put("result","参数异常");
        }else if(ids==null||ids.length<=0)
        {
            resultMap.put("result","请给角色至少分配一个权限");
        }else
        {
            String roleName = request.getParameter("roleName").toString();
            String roleRemark = request.getParameter("roleRemark").toString();
            AdminUser adminUser = (AdminUser)request.getSession().getAttribute("adminUser");
            if(adminUser!=null){
                Role role = roleService.findRoleByRoleName(roleName);
                if(role==null){
                    Role role2 = new Role();
                    role2.setRoleName(roleName);
                    role2.setRoleRemark(roleRemark);
                    int count = roleService.addRole(role2,ids);
                    if(count>0){
                        resultMap.put("result","SUCCESS");
                    }else
                    {
                        resultMap.put("result","操作失败");
                    }
                }else
                {
                    resultMap.put("result","角色已存在");
                }

            }else
            {
                resultMap.put("result","登录超时,请重新登录");
            }
        }

        return resultMap;
    }

 

页面的展示:

role_add.jsp

<%--
  Created by IntelliJ IDEA.
  User: shaojiang
  Date: 2019/1/26
  Time: 下午2:43
  To change this template use File | Settings | File Templates.
--%>
<%--
  Created by IntelliJ IDEA.
  User: shaojiang
  Date: 2018/12/22
  Time: 下午9:32
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!--_meta 作为公共模版分离出去-->
<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
    <meta name="renderer" content="webkit|ie-comp|ie-stand">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no" />
    <meta http-equiv="Cache-Control" content="no-siteapp" />
    <link rel="Bookmark" href="/favicon.ico" >
    <link rel="Shortcut Icon" href="/favicon.ico" />
    <!--[if lt IE 9]>
    <script type="text/javascript" src="/statics/lib/html5shiv.js"></script>
    <script type="text/javascript" src="/statics/lib/respond.min.js"></script>
    <![endif]-->
    <link rel="stylesheet" type="text/css" href="/statics/h-ui/css/H-ui.min.css" />
    <link rel="stylesheet" type="text/css" href="/statics/h-ui.admin/css/H-ui.admin.css" />
    <link rel="stylesheet" type="text/css" href="/statics/lib/Hui-iconfont/1.0.8/iconfont.css" />
    <link rel="stylesheet" type="text/css" href="/statics/h-ui.admin/skin/default/skin.css" id="skin" />
    <link rel="stylesheet" type="text/css" href="/statics/h-ui.admin/css/style.css" />
    <%--zTree样式表--%>
    <link rel="stylesheet" type="text/css" href="/statics/lib/zTree/v3/css/zTreeStyle/zTreeStyle.css" />
    <!--[if IE 6]>
    <script type="text/javascript" src="/statics/lib/DD_belatedPNG_0.0.8a-min.js" ></script>
    <script>DD_belatedPNG.fix(*);</script>
    <![endif]-->
    <!--/meta 作为公共模版分离出去-->
    <title>H-ui.admin v3.1</title>
</head>
<body>
<article class="page-container">
    <form:form modelAttribute="role" action="##" onsubmit="return false" class="form form-horizontal" id="form-role-add">
        <div class="row cl">
            <label class="form-label col-xs-4 col-sm-3"><span class="c-red">*</span>角色名称:</label>
            <div class="formControls col-xs-8 col-sm-9">
                    <%--<input type="text" class="input-text" value="${requestScope.role.roleName}" placeholder="" id="roleName" name="roleName">--%>
                <form:input path="roleName" cssClass="input-text"/>
            </div>
        </div>
        <div class="row cl">
            <label class="form-label col-xs-4 col-sm-3">角色备注:</label>
            <div class="formControls col-xs-8 col-sm-9">
                    <%--<input type="text" class="input-text" value="${requestScope.role.remark}" placeholder="" id="" name="">--%>
                <form:input path="roleRemark" cssClass="input-text"/>
            </div>
        </div>
        <div class="row cl">
            <label class="form-label col-xs-4 col-sm-3">资源权限:</label>
            <ul class=" formControls col-xs-8 col-sm-9">

                <c:forEach  var="item"  items="${requestScope.permissionsList}" begin="0">
                    <dl class="permission-list">
                        <dt>
                            <label>
                                <input type="checkbox" value="${item.id}" name="pers">
                                    ${item.name}</label>
                        </dt>
                        <dd>
                            <c:forEach var="sub_item" items="${item.childPermissions}" begin="0" >
                                <dl class="cl permission-list2">
                                    <dt>
                                        <label class="">
                                            <input type="checkbox" value="${sub_item.id}" name="pers">
                                                ${sub_item.name}</label>
                                    </dt>
                                    <dd>
                                        <c:forEach var="sub_subitem" items="${sub_item.childPermissions}" begin="0" >
                                            <label class="">
                                                <input type="checkbox" value="${sub_subitem.id}" name="pers">
                                                    ${sub_subitem.name}</label>
                                        </c:forEach>
                                    </dd>
                                </dl>
                            </c:forEach>
                        </dd>
                    </dl>
                </c:forEach>

            </div>
        </div>
        <div class="row cl">
            <div class="col-xs-8 col-sm-9 col-xs-offset-4 col-sm-offset-3">
                <button type="button" class="btn btn-success radius" id="role-save" name="admin-role-save"><i class="icon-ok"></i> 确定</button>
            </div>
        </div>
    </form:form>
</article>

<!--请在下方写此页面业务相关的脚本-->
<script type="text/javascript" src="/statics/lib/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="/statics/lib/plug-ins/pagination/pagination.js"></script>
<script type="text/javascript" src="/statics/lib/layer/2.4/layer.js"></script>
<script type="text/javascript" src="/statics/lib/zTree/v3/js/jquery.ztree.core-3.5.min.js"></script>
<script type="text/javascript" src="/statics/lib/zTree/v3/js/jquery.ztree.excheck-3.5.min.js"></script>
<script type="text/javascript">


    $(function(){

        $(".permission-list dt input:checkbox").click(function(){
            $(this).closest("dl").find("dd input:checkbox").prop("checked",$(this).prop("checked"));
        });

        $(".permission-list2 dt input:checkbox").click(function(){

            var l =$(this).parent().find("input:checked").length;
            var l2=$(this).parents(".permission-list").find(".permission-list2 dd").find("input:checked").length;

            if($(this).prop("checked")){
                $(this).closest("dl").find("dt input:checkbox").prop("checked",true);
                $(this).parents(".permission-list").find("dt").first().find("input:checkbox").prop("checked",true);
            }
            else{
                if(l==0){
                    $(this).closest("dl").find("dt input:checkbox").prop("checked",false);
                }
                if(l2==0){
                    $(this).parents(".permission-list").find("dt").first().find("input:checkbox").prop("checked",false);
                }
            }
        });

        $(".permission-list2 dd input:checkbox").click(function(){
            var l =$(this).parent().parent().find("input:checked").length;
            var l2=$(this).parents(".permission-list").find(".permission-list2 dd").find("input:checked").length;

            if($(this).prop("checked")){
                $(this).closest("dl").find("dt input:checkbox").prop("checked",true);
                $(this).parents(".permission-list").find("dt").first().find("input:checkbox").prop("checked",true);
            }
            else{
                if(l==0){
                    $(this).closest("dl").find("dt input:checkbox").prop("checked",false);
                }
                if(l2==0){
                    $(this).parents(".permission-list").find("dt").first().find("input:checkbox").prop("checked",false);
                }
            }
        });




        $("#role-save").click(function () {


            //第二种方法获取全部选中的ID
            var values = $("input[name=‘pers‘]:checked").map(function(){
                return $(this).val();
            }).get();

            var roleName = $("#roleName").val();
            var roleRemark = $("#roleRemark").val();
            if(!roleName){
                layer.msg("请输入角色名称");
                $("#roleName").select();
                return false;
            }else if(roleName.length>12)
            {
                layer.msg("不能超过12个字符");
                $("#roleName").select();
                return false;
            }else if(!roleRemark){
                layer.msg("请输入角色备注");
                $("#roleRemark").select();
                return false;
            }else if(roleRemark.length>12)
            {
                layer.msg("不能超过30个字符");
                $("#roleRemark").select();
                return false;
            }else if(values.length<=0)
            {
                layer.msg("请给角色至少分配一个权限");
                return false;
            }else
            {
                //提交表单
                var yesForm = $("#form-role-add").serialize();
                alert(yesForm);

                $.ajax({
                    //几个参数需要注意一下
                    type: "POST",//方法类型
                    dataType: "json",//预期服务器返回的数据类型
                    url: "/admin/role/role-add.action" ,//url
                    data:yesForm,
                    success: function (data) {
                        console.log(data.result);//打印服务端返回的数据(调试用)
                        if (data.result == SUCCESS||data.result == 200) {
                            layer.msg("保存成功",{icon:1,time:2000});
                        }else
                        {
                            layer.msg("保存失败:"+data.result.toString(),{icon:5,time:2000});
                        }
                    },
                    error : function() {
                        layer.msg(data.result.toString());
                    }
                });
            }


        });


    });










//    var setting = {
//        view: {
//            dblClickExpand: true,//双击节点时,是否自动展开父节点的标识
//            showLine: true,//是否显示节点之间的连线
//            fontCss:{‘color‘:‘black‘,‘font-weight‘:‘bold‘},//字体样式函数
//            selectedMulti: false //设置是否允许同时选中多个节点
//        },
//        check:{
//            //chkboxType: { "Y": "ps", "N": "ps" },
//            chkStyle: "checkbox",//复选框类型
//            enable: true //每个节点上是否显示 CheckBox
//        },
//        data: {
//            simpleData: {//简单数据模式
//                enable:true,
//                idKey: "id",
//                pIdKey: "parentId",
//                rootPId: ""
//            }
//        },
//        callback: {
//            beforeClick: function(treeId, treeNode) {
//                zTree = $.fn.zTree.getZTreeObj("per_tree");
//                if (treeNode.isParent) {
//                    zTree.expandNode(treeNode);//如果是父节点,则展开该节点
//                }else{
//                    zTree.checkNode(treeNode, !treeNode.checked, true, true);//单击勾选,再次单击取消勾选
//                }
//            }
//        }//每个节点上是否显示 CheckBox
//    };
//
//    function onCheck(e,treeId,treeNode){
//        var treeObj=$.fn.zTree.getZTreeObj("per_tree"),
//            nodes=treeObj.getCheckedNodes(true),
//            v="";
//        for(var i=0;i<nodes.length;i++){
//            v+=nodes[i].name + ",";
//            alert(nodes[i].id); //获取选中节点的值
//        }
//    }
//
//
//    function loadPerData() {
//
//        var treeNodes;
//
//        $.ajax({
//            async:false,//是否异步
//            cache:false,//是否使用缓存
//            type:‘POST‘,//请求方式:post
//            dataType:‘json‘,//数据传输格式:json
//            url:‘/admin/per/loadPermissionZTree.action‘,//请求的action路径
//            error:function(){
//                //请求失败处理函数
//                layer.msg("请求失败",{icon:5,time:3000});
//            },
//            success:function(data){
//                //console.log(data);
//                alert(data.toString());
//                //请求成功后处理函数
//                treeNodes = data;//把后台封装好的简单Json格式赋给treeNodes
//            }
//        });
//
//        //初始化zTree,展开所有节点
//        var t = $("#per_tree");
//        t = $.fn.zTree.init(t, setting, treeNodes).expandAll(true);
//
//
//    }
//
//    $(function(){
//        //从数据库获取所有权限数据加载到配置属性zNodes中
//        loadPerData();
//    });
</script>
<!--/请在上方写此页面业务相关的脚本-->
</body>
</html>

 

 

 

 

 

 

 

 

 

下图使用了Ztree展示树

 

技术图片

 

ztree_role_add.jsp页面部分:

 

<%--
  Created by IntelliJ IDEA.
  User: shaojiang
  Date: 2019/1/26
  Time: 下午2:43
  To change this template use File | Settings | File Templates.
--%>
<%--
  Created by IntelliJ IDEA.
  User: shaojiang
  Date: 2018/12/22
  Time: 下午9:32
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!--_meta 作为公共模版分离出去-->
<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
    <meta name="renderer" content="webkit|ie-comp|ie-stand">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no" />
    <meta http-equiv="Cache-Control" content="no-siteapp" />
    <link rel="Bookmark" href="/favicon.ico" >
    <link rel="Shortcut Icon" href="/favicon.ico" />
    <!--[if lt IE 9]>
    <script type="text/javascript" src="/statics/lib/html5shiv.js"></script>
    <script type="text/javascript" src="/statics/lib/respond.min.js"></script>
    <![endif]-->
    <link rel="stylesheet" type="text/css" href="/statics/h-ui/css/H-ui.min.css" />
    <link rel="stylesheet" type="text/css" href="/statics/h-ui.admin/css/H-ui.admin.css" />
    <link rel="stylesheet" type="text/css" href="/statics/lib/Hui-iconfont/1.0.8/iconfont.css" />
    <link rel="stylesheet" type="text/css" href="/statics/h-ui.admin/skin/default/skin.css" id="skin" />
    <link rel="stylesheet" type="text/css" href="/statics/h-ui.admin/css/style.css" />
    <%--zTree样式表--%>
    <link rel="stylesheet" type="text/css" href="/statics/lib/zTree/v3/css/zTreeStyle/zTreeStyle.css" />
    <!--[if IE 6]>
    <script type="text/javascript" src="/statics/lib/DD_belatedPNG_0.0.8a-min.js" ></script>
    <script>DD_belatedPNG.fix(*);</script>
    <![endif]-->
    <!--/meta 作为公共模版分离出去-->
    <title>H-ui.admin v3.1</title>
    <style>
        <%--修改ztree显示样式--%>
        ul.ztree li span.button.switch{margin-right:5px}
        ul.ztree ul ul li{display:inline-block;white-space:normal}
        ul.ztree>li>ul>li{padding:5px}
        ul.ztree>li{background: #dae6f0}
        ul.ztree>li:nth-child(even)>ul>li:nth-child(even){background: #eef5fa}
        ul.ztree>li:nth-child(even)>ul>li:nth-child(odd){background: #f6fbff}
        ul.ztree>li:nth-child(odd)>ul>li:nth-child(even){background: #eef5fa}
        ul.ztree>li:nth-child(odd)>ul>li:nth-child(odd){background: #f6fbff}
        ul.ztree>li>ul{margin-top:12px}
        ul.ztree>li{padding:15px;padding-right:25px}
        ul.ztree li{white-space:normal!important}
        ul.ztree>li>a>span{font-size:15px;font-weight:700}
    </style>
</head>
<body>
<article class="page-container">
    <form:form modelAttribute="role" action="##" onsubmit="return false" class="form form-horizontal" id="form-role-add">
        <div class="row cl">
            <label class="form-label col-xs-4 col-sm-3"><span class="c-red">*</span>角色名称:</label>
            <div class="formControls col-xs-8 col-sm-9">
                    <%--<input type="text" class="input-text" value="${requestScope.role.roleName}" placeholder="" id="roleName" name="roleName">--%>
                <form:input path="roleName" cssClass="input-text"/>
            </div>
        </div>
        <div class="row cl">
            <label class="form-label col-xs-4 col-sm-3">角色备注:</label>
            <div class="formControls col-xs-8 col-sm-9">
                    <%--<input type="text" class="input-text" value="${requestScope.role.remark}" placeholder="" id="" name="">--%>
                <form:input path="roleRemark" cssClass="input-text"/>
            </div>
        </div>
        <div class="row cl">
            <label class="form-label col-xs-4 col-sm-3">资源权限:</label>
            <ul class=" formControls col-xs-8 col-sm-9">

                <div>
                    <ul class="ztree" id="perZtree" >
                    </ul>
                </div>
            </ul>

        </div>
        </div>
        <div class="row cl">
            <div class="col-xs-8 col-sm-9 col-xs-offset-4 col-sm-offset-3">
                <button type="button" class="btn btn-success radius" id="role-save" name="admin-role-save"><i class="icon-ok"></i> 确定</button>
            </div>
        </div>
    </form:form>
</article>

<!--请在下方写此页面业务相关的脚本-->
<script type="text/javascript" src="/statics/lib/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="/statics/lib/plug-ins/pagination/pagination.js"></script>
<script type="text/javascript" src="/statics/lib/layer/2.4/layer.js"></script>
<script type="text/javascript" src="/statics/lib/zTree/v3/js/jquery.ztree.core-3.5.min.js"></script>
<script type="text/javascript" src="/statics/lib/zTree/v3/js/jquery.ztree.excheck-3.5.min.js"></script>
<script type="text/javascript">

    var values;


    $(function(){
        //从数据库获取所有权限数据加载到配置属性zNodes中
        loadPerData();


        $("#role-save").click(function()
        {
            var values="";
            var treeObj=$.fn.zTree.getZTreeObj("perZtree");
            var nodes=treeObj.getCheckedNodes(true);
            for(var i=0;i<nodes.length;i++){
                values+=nodes[i].id + ",";
            }

            values=values.substr(0,values.length-1);


            var roleName = $("#roleName").val();
            var roleRemark = $("#roleRemark").val();
            if(!roleName){
                layer.msg("请输入角色名称");
                $("#roleName").select();
                return false;
            }else if(roleName.length>12)
            {
                layer.msg("不能超过12个字符");
                $("#roleName").select();
                return false;
            }else if(!roleRemark){
                layer.msg("请输入角色备注");
                $("#roleRemark").select();
                return false;
            }else if(roleRemark.length>12)
            {
                layer.msg("不能超过30个字符");
                $("#roleRemark").select();
                return false;
            }else if(values.length<=0)
            {
                layer.msg("请给角色至少分配一个权限");
                return false;
            }else
            {

                var formStr = "roleName="+roleName+"&";
                formStr += "roleRemark="+roleRemark+"&";
                formStr += "pers="+values;
                //提交表单
//                var yesForm = $("#form-role-add").serialize();
                alert(formStr);

                $.ajax({
                    //几个参数需要注意一下
                    type: "POST",//方法类型
                    dataType: "json",//预期服务器返回的数据类型
                    url: "/admin/role/ztree-role-add.action" ,//url
                    data:formStr,
                    success: function (data) {
                        console.log(data.result);//打印服务端返回的数据(调试用)
                        if (data.result == SUCCESS||data.result == 200) {
                            layer.msg("保存成功",{icon:1,time:2000});
                        }else
                        {
                            layer.msg("保存失败:"+data.result.toString(),{icon:5,time:2000});
                        }
                    },
                    error : function() {
                        layer.msg(data.result.toString());
                    }
                });
            }

        });
    });



    function onCheck(e,treeId,treeNode){
        var treeObj=$.fn.zTree.getZTreeObj("perZtree"),
            nodes=treeObj.getCheckedNodes(true),
            v="";
        for(var i=0;i<nodes.length;i++){
            v+=nodes[i].name + ",";
            console.log(nodes[i].id); //获取选中节点的值
            values.put(nodes[i].id);
        }
    }


    function loadPerData() {

        var treeNodes = [
            {"id":1"pId":0"name":"test1"},
            {"id":11"pId":1"name":"test11"},
            {"id":12"pId":1"name":"test12"},
            {"id":111"pId":11"name":"test111"}
            ];

        var setting = {
            view: {
                dblClickExpand: false,//双击节点时,是否自动展开父节点的标识
                showLine: true,//是否显示节点之间的连线
                fontCss:{color:black,font-weight:bold},//字体样式函数
                selectedMulti: false //设置是否允许同时选中多个节点
            },
            check:{
                //chkboxType: { "Y": "ps", "N": "ps" },
                chkStyle: "checkbox",//复选框类型
                enable: true //每个节点上是否显示 CheckBox
            },
            data: {
                key:{
                    url:"xUrl"//后台数据使用了url,如果不想点击节点后跳转,设置不存在的URL即可
                },
                simpleData: {//简单数据模式
                    enable:true,
                    idKey: "id",
                    pIdKey: "parentId",
                    rootPId: ""
                }
            }
        };


        $.ajax({
            async:false,//是否异步
            cache:false,//是否使用缓存
            type:POST,//请求方式:post
            dataType:json,//数据传输格式:json
            url:/admin/role/loadPermissionZTree.action,//请求的action路径
            error:function(){
                //请求失败处理函数
                layer.msg("请求失败",{icon:5,time:3000});
            },
            success:function(data){
                //console.log(data);
                //alert(data.toString());
                //请求成功后处理函数
                treeNodes = data;//把后台封装好的简单Json格式赋给treeNodes
            }
        });

        //初始化zTree,展开所有节点
        var t = $("#perZtree");
        t = $.fn.zTree.init(t, setting, treeNodes).expandAll(true);


    }

</script>
<!--/请在上方写此页面业务相关的脚本-->
</body>
</html>

 

/**
     * 加载所有权限树
     * @return
     */
    @AccessPermissionsInfo("role:list")
    @RequestMapping(value = "/loadPermissionZTree.action",method = RequestMethod.POST)
    @ResponseBody
    public List<Permission> loadPermissionZTree()
    {
        //获取所有权限集合
        List<Permission> allPermissionsList =
                permissionService.findAllPermission();
        return allPermissionsList;
    }

 

 /**
     * ztree样式添加角色信息
     * @param request
     * @return
     */
    @AccessPermissionsInfo("role:add")
    @RequestMapping(value = "/ztree-role-add.action",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> zTreeRoleAdd(HttpServletRequest request)
    {
        Map<String,Object> resultMap = new HashMap<String,Object>();

        String ids = request.getParameter("pers");
        //转换成数组
        String[] pers = ids.split(",");

        if(request.getParameter("roleName")==null||
                request.getParameter("roleRemark")==null)
        {
            resultMap.put("result","参数异常");
        }else if(pers==null||pers.length<=0)
        {
            resultMap.put("result","请给角色至少分配一个权限");
        }else
        {
            String roleName = request.getParameter("roleName").toString();
            String roleRemark = request.getParameter("roleRemark").toString();
            AdminUser adminUser = (AdminUser)request.getSession().getAttribute("adminUser");
            if(adminUser!=null){
                Role role = roleService.findRoleByRoleName(roleName);
                if(role==null){
                    Role role2 = new Role();
                    role2.setRoleName(roleName);
                    role2.setRoleRemark(roleRemark);
                    int count = roleService.addRole(role2,pers);
                    if(count>0){
                        resultMap.put("result","SUCCESS");
                    }else
                    {
                        resultMap.put("result","操作失败");
                    }
                }else
                {
                    resultMap.put("result","角色已存在");
                }

            }else
            {
                resultMap.put("result","登录超时,请重新登录");
            }
        }

        return resultMap;
    }

 

不管使用哪种方式添加和展示,这里面最终都调用了这两个方法:roleService.findRoleByRoleName(roleName)和roleService.addRole(role2,pers);

 

 

 

 

 /**
     * 添加角色
     *
     * @param role 角色信息
     * @param ids  角色关联的权限ID数组
     * @return
     */
    @Override
    public int addRole(Role role, String[] ids) {

        //执行成功条数
        int successCount = 0;
        //添加角色信息
        successCount = roleDao.addRole(role);

        //取得添加成功后返回的ID编号
        String roleId = role.getId().toString();

        //循环遍历权限ID数组,执行插入角色权限关联信息
        for (String pId :ids)
        {
            successCount +=roleDao.addRolePermissionRelation(roleId,pId);
        }

        return successCount;
    }

 

 

 

持久层:

 

<!--对应RoleDao接口文件中的findRoleByRoleName方法,参数类型string-->
    <select id="findRoleByRoleName" parameterType="string"
            resultType="com.supin51.domain.Role" >
        SELECT * FROM t_role
        WHERE roleName = #{roleName}
    </select>

 

 <!--对应RoleDao接口文件中的addRole方法,参数类型role,使用主键自增,返回新增主键-->
    <insert id="addRole" useGeneratedKeys="true" keyProperty="id" keyColumn="id" >

        <!--order="BEFORE"会在insert语句之前执行,使用selectKey元素自定义主键的生成
            返回要插入的ID,如果没有记录,返回ID为1,否则返回最后的ID+1(每次插入递增1),这样可以自定义ID编号规则-->
        <selectKey keyProperty="id" resultType="int" order="BEFORE" statementType="PREPARED" >
            SELECT if(MAX(id)=NULL,1,MAX(id)+1) FROM t_role
        </selectKey>

        <!--注意这里使用了动态插入sql-->
        INSERT INTO t_role
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="id != null"> id, </if>
            <if test="roleName != null">roleName,</if>
            <if test="roleRemark != null">roleRemark, </if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
            <if test="id != null"> #{id,jdbcType=BIGINT},</if>
            <if test="roleName != null">#{roleName,jdbcType=VARCHAR},</if>
            <if test="roleRemark != null">#{roleRemark,jdbcType=VARCHAR}, </if>
        </trim>
    </insert>

 

 

角色的删除

 

 /**
     * 删除角色信息
     * @param request
     * @return
     */
    @AccessPermissionsInfo("role:delete")
    @RequestMapping(value = "/role-delete.action",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> deleteAdminUser(HttpServletRequest request)
    {
        //接收角色编号
        String str_ids = request.getParameter("ids");
        str_ids = str_ids.replace("/","");//替换掉/
        //转换成数组
        String[] ids = str_ids.split(","); // 用,分割
        //logger.info(Arrays.toString(ids));

        Map<String,Object> resultMap = new HashMap<String,Object>();

        if(ids==null||ids.length<=0)
        {
            resultMap.put("result","参数异常");
        }else
        {
            AdminUser adminUser = (AdminUser)request.getSession().getAttribute("adminUser");
            if(adminUser!=null){
                //执行删除角色
                int count = roleService.deleteRole(ids);
                if(count>0){
                    resultMap.put("result","SUCCESS");
                }else
                {
                    resultMap.put("result","操作失败");
                }

            }else
            {
                resultMap.put("result","登录超时,请重新登录");
            }
        }

        return resultMap;
    }

 

RoleServiceImpl部分

/**
     * 删除角色
     *
     * @param ids 角色编号数组
     * @return
     */
    @Override
    public int deleteRole(String[] ids) {

        int successCount = 0;

        //遍历角色组
        for(String roleId:ids)
        {
            //查找角色下的管理用户列表
            List<AdminUser> adminUserList =
                    adminUserService.findAdminUserListByRoleId(roleId);
            //遍历用户列表
            for (AdminUser adminUser:adminUserList)
            {
                //根据用户查询用户的角色数,一个用户可能有多个角色
                List<String> roles =
                        adminUserService.findAdminUserRoleListByAdminId(adminUser.getId());
                //如果用户的角色大于1个
                if(roles.size()>1){
                    //执行删除当前角色操作
                    //根据角色编号和用户编号,删除(用户和角色中间表)的关联信息,adminUser.id 和 roleId
                    successCount+=roleDao.deleteRoleAdminRelationByRoleIds(adminUser.getId(),roleId);
                }else
                {
                    //如果用户的角色只有一个,就更新用户的最后一个角色至未分组,adminUser.id 和roleId
                    successCount+=roleDao.updateRoleAdminRelationByRoleIds(adminUser.getId(),roleId);
                }
            }
        }

        //删除角色权限表中的角色和权限关联信息
        successCount+=roleDao.deleteRolePermissionRelationByRoleIds(ids);

        //删除角色信息
        successCount+=roleDao.deleteRoleByRoleIds(ids);


        return successCount;
    }

 

持久层

  <!--对应AdminUserDao接口文件中的findAdminUserRoleListByAdminId方法-->
    <select id="findAdminUserRoleListByAdminId" parameterType="int"
            resultType="string" >
        SELECT tr.roleName
        FROM t_role tr
        LEFT JOIN t_admin_role tar
        ON tar.roleId = tr.id
        LEFT JOIN t_admin ta
        ON tar.adminId = ta.id
        WHERE ta.id = #{adminId}
    </select>

 

 <!--对应RoleDao接口文件中的updateRoleAdminRelationByRoleIds方法-->
    <update id="updateRoleAdminRelationByRoleIds">
        UPDATE t_admin_role
        SET roleId = 2
        WHERE roleId = #{roleId} AND adminId = #{id}
    </update>



    <!--对应RoleDao接口文件中的deleteRoleAdminRelationByRoleIds方法-->
    <delete id="deleteRoleAdminRelationByRoleIds">
        DELETE FROM t_admin_role
        WHERE roleId = #{roleId} AND adminId = #{id}
    </delete>

 

 

编辑角色:

 

<%--
  Created by IntelliJ IDEA.
  User: shaojiang
  Date: 2019/1/27
  Time: 下午4:51
  To change this template use File | Settings | File Templates.
--%>
<%--
  Created by IntelliJ IDEA.
  User: shaojiang
  Date: 2019/1/26
  Time: 下午2:43
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!--_meta 作为公共模版分离出去-->
<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
    <meta name="renderer" content="webkit|ie-comp|ie-stand">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no" />
    <meta http-equiv="Cache-Control" content="no-siteapp" />
    <link rel="Bookmark" href="/favicon.ico" >
    <link rel="Shortcut Icon" href="/favicon.ico" />
    <!--[if lt IE 9]>
    <script type="text/javascript" src="/statics/lib/html5shiv.js"></script>
    <script type="text/javascript" src="/statics/lib/respond.min.js"></script>
    <![endif]-->
    <link rel="stylesheet" type="text/css" href="/statics/h-ui/css/H-ui.min.css" />
    <link rel="stylesheet" type="text/css" href="/statics/h-ui.admin/css/H-ui.admin.css" />
    <link rel="stylesheet" type="text/css" href="/statics/lib/Hui-iconfont/1.0.8/iconfont.css" />
    <link rel="stylesheet" type="text/css" href="/statics/h-ui.admin/skin/default/skin.css" id="skin" />
    <link rel="stylesheet" type="text/css" href="/statics/h-ui.admin/css/style.css" />
    <%--zTree样式表--%>
    <link rel="stylesheet" type="text/css" href="/statics/lib/zTree/v3/css/zTreeStyle/zTreeStyle.css" />
    <!--[if IE 6]>
    <script type="text/javascript" src="/statics/lib/DD_belatedPNG_0.0.8a-min.js" ></script>
    <script>DD_belatedPNG.fix(*);</script>
    <![endif]-->
    <!--/meta 作为公共模版分离出去-->
    <title>H-ui.admin v3.1</title>
    <style>
        <%--修改ztree显示样式--%>
        ul.ztree li span.button.switch{margin-right:5px}
        ul.ztree ul ul li{display:inline-block;white-space:normal}
        ul.ztree>li>ul>li{padding:5px}
        ul.ztree>li{background: #dae6f0}
        ul.ztree>li:nth-child(even)>ul>li:nth-child(even){background: #eef5fa}
        ul.ztree>li:nth-child(even)>ul>li:nth-child(odd){background: #f6fbff}
        ul.ztree>li:nth-child(odd)>ul>li:nth-child(even){background: #eef5fa}
        ul.ztree>li:nth-child(odd)>ul>li:nth-child(odd){background: #f6fbff}
        ul.ztree>li>ul{margin-top:12px}
        ul.ztree>li{padding:15px;padding-right:25px}
        ul.ztree li{white-space:normal!important}
        ul.ztree>li>a>span{font-size:15px;font-weight:700}
    </style>
</head>
<body>
<article class="page-container">
    <form:form modelAttribute="role" action="##" onsubmit="return false" class="form form-horizontal" id="form-role-add">
        <div class="row cl">
            <label class="form-label col-xs-4 col-sm-3"><span class="c-red">*</span>角色名称:</label>
            <div class="formControls col-xs-8 col-sm-9">
                    <%--<input type="text" class="input-text" value="${requestScope.role.roleName}" placeholder="" id="roleName" name="roleName">--%>
                <form:hidden path="id" />
                <form:input path="roleName" cssClass="input-text"/>
            </div>
        </div>
        <div class="row cl">
            <label class="form-label col-xs-4 col-sm-3">角色备注:</label>
            <div class="formControls col-xs-8 col-sm-9">
                    <%--<input type="text" class="input-text" value="${requestScope.role.remark}" placeholder="" id="" name="">--%>
                <form:input path="roleRemark" cssClass="input-text"/>
            </div>
        </div>
        <div class="row cl">
            <label class="form-label col-xs-4 col-sm-3">资源权限:</label>
            <ul class=" formControls col-xs-8 col-sm-9">

                <div>
                    <ul class="ztree" id="perZtree" >
                    </ul>
                </div>
            </ul>

        </div>
        </div>
        <div class="row cl">
            <div class="col-xs-8 col-sm-9 col-xs-offset-4 col-sm-offset-3">
                <button type="button" class="btn btn-success radius" id="role-save" name="admin-role-save"><i class="icon-ok"></i> 确定</button>
            </div>
        </div>
    </form:form>
</article>

<!--请在下方写此页面业务相关的脚本-->
<script type="text/javascript" src="/statics/lib/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="/statics/lib/plug-ins/pagination/pagination.js"></script>
<script type="text/javascript" src="/statics/lib/layer/2.4/layer.js"></script>
<script type="text/javascript" src="/statics/lib/zTree/v3/js/jquery.ztree.core-3.5.min.js"></script>
<script type="text/javascript" src="/statics/lib/zTree/v3/js/jquery.ztree.excheck-3.5.min.js"></script>
<script type="text/javascript">

    var values;

    $(function(){
        //从数据库获取所有权限数据加载到配置属性zNodes中
        loadPerData();


        $("#role-save").click(function()
        {
            var values="";
            var treeObj=$.fn.zTree.getZTreeObj("perZtree");
            var nodes=treeObj.getCheckedNodes(true);
            for(var i=0;i<nodes.length;i++){
                values+=nodes[i].id + ",";
            }

            values=values.substr(0,values.length-1);

            var roleId = $("#id").val();
            var roleName = $("#roleName").val();
            var roleRemark = $("#roleRemark").val();
            if(!roleId){
                layer.msg("缺少角色主键");
                return false;
            }
            if(!roleName){
                layer.msg("请输入角色名称");
                $("#roleName").select();
                return false;
            }else if(roleName.length>12)
            {
                layer.msg("不能超过12个字符");
                $("#roleName").select();
                return false;
            }else if(!roleRemark){
                layer.msg("请输入角色备注");
                $("#roleRemark").select();
                return false;
            }else if(roleRemark.length>12)
            {
                layer.msg("不能超过30个字符");
                $("#roleRemark").select();
                return false;
            }else if(values.length<=0)
            {
                layer.msg("请给角色至少分配一个权限");
                return false;
            }else
            {

                var formStr = "roleId="+roleId+"&";
                formStr += "roleName="+roleName+"&";
                formStr += "roleRemark="+roleRemark+"&";
                formStr += "pers="+values;
                //提交表单
                // var yesForm = $("#form-role-add").serialize();
                alert(formStr);

                parent.layer.confirm(确定提交保存?,function(index) {

                    $.ajax({
                        //几个参数需要注意一下
                        type: "POST",//方法类型
                        dataType: "json",//预期服务器返回的数据类型
                        url: "/admin/role/zTree-role-edit.action" ,//url
                        data:formStr,
                        success: function (data) {
                            console.log(data.result);//打印服务端返回的数据(调试用)
                            if (data.result == SUCCESS||data.result == 200) {
                                parent.layer.close(index);//关闭弹窗
                                layer.msg("保存成功",{icon:1,time:2000});
                            }else
                            {
                                layer.msg("保存失败:"+data.result.toString(),{icon:5,time:2000});
                            }
                        },
                        error : function() {
                            layer.msg(data.result.toString());
                        }
                    });
                });

            }

        });
    });



    function loadPerData() {

        var roleId = $("#id").val();
        //alert(roleId);
        var treeNodes;
        if(roleId){
            //请求获取角色下的权限列表
            $.ajax({
                async:false,//是否异步
                cache:false,//是否使用缓存
                type:POST,//请求方式:post
                dataType:json,//数据传输格式:json
                url:/admin/role/loadRolePermissionZTree.action/+roleId.toString(),//请求的action路径
                error:function(){
                    //请求失败处理函数
                    layer.msg("请求角色权限失败",{icon:5,time:3000});
                },
                success:function(data){
                    //console.log(data);
                    //alert(data.toString());
                    //请求成功后处理函数
                    treeNodes = data;//把后台封装好的简单Json格式赋给treeNodes
                }
            });
        }


        //alert(treeNodes.toString());


//        var treeNodes = [
//            {"id":1, "pId":0, "name":"test1"},
//            {"id":11, "pId":1, "name":"test11"},
//            {"id":12, "pId":1, "name":"test12"},
//            {"id":111, "pId":11, "name":"test111"}
//        ];

        var setting = {
            view: {
                dblClickExpand: false,//双击节点时,是否自动展开父节点的标识
                showLine: true,//是否显示节点之间的连线
                fontCss:{color:black,font-weight:bold},//字体样式函数
                selectedMulti: false //设置是否允许同时选中多个节点
            },
            check:{
                //chkboxType: { "Y": "ps", "N": "ps" },
                chkStyle: "checkbox",//复选框类型
                enable: true //每个节点上是否显示 CheckBox
            },
            data: {
                key:{
                    url:"xUrl"//后台数据使用了url,如果不想点击节点后跳转,设置不存在的URL即可
                },
                simpleData: {//简单数据模式
                    enable:true,
                    idKey: "id",
                    pIdKey: "parentId",
                    rootPId: ""
                }
            }
        };


        $.ajax({
            async:false,//是否异步
            cache:false,//是否使用缓存
            type:POST,//请求方式:post
            dataType:json,//数据传输格式:json
            url:/admin/per/loadPermissionZTree.action,//请求的action路径
            error:function(){
                //请求失败处理函数
                layer.msg("请求失败",{icon:5,time:3000});
            },
            success:function(data){
                //console.log(data);
                //alert(data.toString());
                //请求成功后处理函数
                //初始化zTree,展开所有节点
                $.fn.zTree.init($("#perZtree"), setting, data).expandAll(true);
            }
        });


        //获取ztree对象
        var treeObj=$.fn.zTree.getZTreeObj("perZtree");
        //alert(treeNodes.toString());
        //遍历需要选中的角色节点,然后利用该节点ID获得与他相同的tree中的节点,设置为选中
        if(treeNodes!=null&&treeNodes.length>0){
            for(var i = 0;i<treeNodes.length;i++){
                var nodes = treeObj.getNodesByParam("id",treeNodes[i].id.toString(),null);
                //勾选当前选中的节点
                treeObj.checkNode(nodes[0], true, false);
            }
        }


    }

</script>
<!--/请在上方写此页面业务相关的脚本-->
</body>
</html>

 

 

/**
     * ztree样式编辑角色信息
     * @param request
     * @param model
     * @return
     */
    @AccessPermissionsInfo("role:edit")
    @RequestMapping(value = "/zTree-role-edit.action",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> zTreeEditRole(HttpServletRequest request,Model model){

        Map<String,Object> resultMap = new HashMap<String ,Object>();

        String ids = request.getParameter("pers");
        //转换成数组
        String[] pers = ids.split(",");

        if(request.getParameter("roleId")==null||
                request.getParameter("roleName")==null||
                request.getParameter("roleRemark")==null){
            resultMap.put("result","参数不合法");
        }else if(pers==null ||pers.length<=0){
            resultMap.put("result","请给角色至少分配一个权限");
        }else
        {
            String roleId = request.getParameter("roleId").toString();
            String roleName = request.getParameter("roleName").toString();
            String roleRemark = request.getParameter("roleRemark").toString();
            Role role = new Role();
            role.setId(Integer.parseInt(roleId));
            role.setRoleName(roleName);
            role.setRoleRemark(roleRemark);
            //验证Session是否过期,其实不验证也可以,拦截器中已经进行了拦截
            AdminUser adminUser = (AdminUser)request.getSession().getAttribute("adminUser");
            if(adminUser!=null){
                //查询角色是否存在
                Role role2 = roleService.findRoleByRoleName(roleName);
                if(role2!=null){
                    //编辑角色信息
                    int count = roleService.editRole(role,pers);
                    if(count>0){
                        resultMap.put("result","SUCCESS");
                    }else
                    {
                        resultMap.put("result","操作失败");
                    }
                }else
                {
                    resultMap.put("result","角色不存在");
                }

            }else
            {
                resultMap.put("result","登录超时,请重新登录");
            }

        }

        return resultMap;
    }

 

RoleServiceImpl部分

 /**
     * 编辑角色信息
     *
     * @param role 角色信息
     * @param pers 权限编号数组
     * @return
     */
    @Override
    public int editRole(Role role, String[] pers) {

        int successCount = 0;
        //第一步:更新角色
        successCount+=roleDao.editRole(role);

        //第二步:根据角色编号查询角色已经持有的权限集合
        List<Permission> permissions =
                roleDao.getRolePermissions(role.getId());
        //取出权限ID放入字符串集合中
        List<String> oldPers = new ArrayList<String>();
        for(Permission p:permissions)
        {
            oldPers.add(p.getId().toString());
        }

        //第三步:遍历旧的权限组
        for (String pId:oldPers)
        {
            //将数组装换成集合
            //如果新的权限组中未包含旧的权限ID
            if(!Arrays.asList(pers).contains(pId)){
                //执行删除角色权限的关联,参数1:角色ID,参数2:旧权限ID
                successCount+=roleDao.deleteRolePermissionRelationById(role.getId(),pId);
            }
        }

        //第四步:遍历新的权限组
        for(String pId:pers)
        {   //如果旧的权限中未包含新的权限ID
            if(!oldPers.contains(pId)){
                //执行插入角色权限操作,参数1:角色ID,参数2:新权限ID
                successCount+=roleDao.addRolePermissionRelation(role.getId().toString(),pId);
            }
        }

        return successCount;
    }

 

 

RoleMapper.xml 持久层:

    <!--对应RoleDao接口文件中的editRole方法,参数类型role-->
    <update id="editRole">
        <!--注意这里使用了动态sql-->
        UPDATE t_role
        <set>
            <if test="roleName != null">
                roleName = #{roleName,jdbcType=VARCHAR},
            </if>
            <if test="roleRemark != null">
                roleRemark = #{roleRemark,jdbcType=VARCHAR}
            </if>
        </set>
        WHERE id = #{id}
    </update>
 <!--对应RoleDao接口文件中的getRolePermissions方法,参数:int 角色编号-->
    <select id="getRolePermissions" parameterType="int" resultType="com.supin51.domain.Permission" >
        SELECT tp.*
        FROM t_permission tp
        LEFT JOIN t_role_permission trp
              ON  trp.permissionId = tp.id
        LEFT JOIN t_role tr
              ON  trp.roleId = tr.id
        WHERE tr.id = #{roleId}
    </select>

    <!--对应RoleDao接口文件中的deleteRolePermissionRelationById方法-->
    <delete id="deleteRolePermissionRelationById">
        DELETE FROM t_role_permission
        WHERE roleId = #{roleId} AND permissionId = #{pId}
    </delete>



    <!--对应RoleDao接口文件中的deleteRolePermissionRelationByRoleIds方法-->
    <delete id="deleteRolePermissionRelationByRoleIds">
        DELETE FROM t_role_permission
        WHERE roleId in
        <foreach item="item" index="index" collection="array"
                 open="(" separator="," close=")" >
            #{item}
        </foreach>
    </delete>

 

JavaEE权限管理系统的搭建(八)--------角色的增删改

标签:调试   初始   end   dde   fun   循环   var   登录   加载   

原文地址:https://www.cnblogs.com/shaojiang/p/10349279.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有 京ICP备13008772号-2
迷上了代码!