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

Posted 将哥

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JavaEE权限管理系统的搭建--------角色的增删改相关的知识,希望对你有一定的参考价值。

 

如下图所示,添加角色的同时,要给角色分配权限菜单,关于权限数的显示,我实现了两种方式,普通方式和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); //获取选中节点的值
//        }
//以上是关于JavaEE权限管理系统的搭建--------角色的增删改的主要内容,如果未能解决你的问题,请参考以下文章

JavaEE权限管理系统的搭建--------管理用户的增删改

JavaEE权限管理系统的搭建

JavaEE权限管理系统的搭建

javaEE 用户部门角色权限实体的关系设计与hibernate映射配置文件关系总结

JAVAEE——BOS物流项目12:角色用户管理,使用ehcache缓存,系统菜单根据登录人展示

webapi框架搭建-安全机制-基于角色的权限控制