java web实现用户权限管理
程序员文章站
2024-03-07 09:02:02
最近在做一个网站类型项目,主要负责后台,ui框架选型为jquery easy ui,项目架构为spring mvc + spring jdbc,简单易用好上手!搭建好框架后...
最近在做一个网站类型项目,主要负责后台,ui框架选型为jquery easy ui,项目架构为spring mvc + spring jdbc,简单易用好上手!搭建好框架后开始了第一个任务,设计并实现一套简单的权限管理功能。
一套最基本的权限管理包括用户、角色、资源。
实现效果:
数据库设计,设计如下:
用户:user
角色:role
用户-角色:user_role
资源:resource(包括上级菜单、子菜单、按钮等资源)
角色-资源:role_resource
标准的权限管理系统设计为以上5张表。
注:用户、用户-角色我就不做说明了,这两个是很简单的两块,用户的crud,以及为用户分配角色(多对多的关系)稍微琢磨一下就清楚了,下面都是针对为角色分配权限的实现
后台实现
展示层采用ztree树
role.jsp
<%@ page contenttype="text/html;charset=utf-8"%> <%@ include file="/views/back/include/taglib.jsp"%> <!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta name="decorator" content="back" /> <script type="text/javascript"> //打开菜单窗口 function openmenudialog(){ var selected = $("#list").datagrid('getselected'); if (selected != null) { $("#id").val(selected.id); querymenus(selected.id); $("#menuwindow").window("open"); } else { $.messager.alert('提示', "未选择数据!"); } } //角色-菜单信息入库 function ajaxsubmit(rid,idstr){ $.post("${ctx}/rolemenu/save.jhtml",{"roleid":rid,"ids":idstr},function(obj){ $.messager.alert('提示',obj.msg); $("#menuwindow").window('close'); },'json'); } </script> <!-- ztree --> <script type="text/javascript"> var tree = ""; var setting = { check : { chkboxtype:{"y":"ps","n":"s"},//勾选checkbox对于父子节点的关联关系,取消勾选时不关联父 chkstyle:"checkbox", enable : true //是否复选框 }, //数据 data : { simpledata : { enable : true } } }; //查询菜单信息 function querymenus(roleid){ $.post('${ctx}/role/treedata.jhtml', {'roleid':roleid}, function(znodes) { for (var i = 0; i < znodes.length; i++) { if (znodes[i].isparent) { } else { //znodes[i].icon = "${ctxstatic}/images/532.ico";//设置图标 } } tree = $.fn.ztree.init($("#tree"), setting, znodes); tree.expandall(true);//全部展开 //var nodes = treeobj.getnodes(); }, 'json'); } //获取选中节点 function oncheck(){ var rid = $("#id").val(); var treeobj=$.fn.ztree.getztreeobj("tree"); var nodes=treeobj.getcheckednodes(true); var ids = new array(); for(var i=0;i<nodes.length;i++){ //获取选中节点的值 ids.push(nodes[i].id); // v+=nodes[i].id + ","; //alert(nodes[i].id); } ajaxsubmit(rid,ids); } </script> </head> <body> <!-- 数据表格 --> <table id="list" url='${ctx}/role/list/page.jhtml' method='post' class="easyui-datagrid" style="width:100%;" fitcolumns="true" toolbar='#tb' pagination='true' rownumbers='true' singleselect='true'> <thead> <tr> <th field='name' sortable='true' width='100'>角色名称</th> <th field='description' width='200' align='right'>描述</th> <th field='createtimeformat' width='150' align='center'>创建时间</th> </tr> </thead> </table> <!-- 编辑栏 --> <div id="tb" style="padding:5px 5px;"> <div> <p2p:permission module="role" code="add"><a href="#" class="easyui-linkbutton" iconcls="icon-add" onclick="opencreatedialog();">新增</a></p2p:permission> <p2p:permission module="role" code="edit"><a href="#" class="easyui-linkbutton" iconcls="icon-edit" onclick="openupdatedialog();">编辑</a></p2p:permission> <p2p:permission module="role" code="delete"><a href="#" class="easyui-linkbutton" iconcls="icon-remove" onclick="del();">删除</a></p2p:permission> <p2p:permission module="role" code="authority"><a href="#" class="easyui-linkbutton" iconcls="icon-edit" onclick="openmenudialog();">设置权限</a></p2p:permission> </div> <!-- 搜索项 --> <div style="margin-top:5px;padding-left:5px"> 用户名: <input id="query_name" class="easyui-textbox" type="text" style="width:110px" /> 创建日期: <input id="query_startdate" class="easyui-datebox" style="width:110px"> 至: <input id="query_enddate" class="easyui-datebox" style="width:110px"> <a onclick="reload();" href="#" class="easyui-linkbutton" iconcls="icon-search">查询</a> </div> </div> <!-- 权限窗口 --> <div id="menuwindow" class="easyui-window" title="配置权限" data-options="modal:true,iconcls:'icon-save',footer:'#menuwindowfooter'" style="width:350px;height:420px;padding:10px"> <div id="tree" class="ztree" style="padding: 10px 20px;"></div> </div> <div id="menuwindowfooter" style="padding:5px;text-align:right;"> <a href="#" onclick="oncheck();" class="easyui-linkbutton" data-options="iconcls:'icon-save'">提交</a> </div> </body> </html>
action层
roleaction.java
@requestmapping(value = "/treedata.jhtml") @responsebody public string treedata(httpservletrequest request, model model) { dynamicparams params = new dynamicparams(request); list<map<string, object>> maplist = lists.newarraylist(); params.put("allmenu", "allmenu"); list<menu> list = authmanager.findmenulist(params); list<rolemenu> rolemenus = authmanager.findrolemenulist(params); for (int i = 0; i < list.size(); i++) { menu e = list.get(i); map<string, object> map = maps.newhashmap(); map.put("id", e.getid()); map.put("pid", e.getparentid() != null ? e.getparentid() : 0); map.put("name", e.getname()); for (rolemenu rolemenu : rolemenus) { if (rolemenu.getmenuid() == e.getid()) { map.put("checked", true); } } maplist.add(map); } return tojson(maplist); }
service层
authmanager.java
// 菜单管理 public list<menu> findmenulist(dynamicparams params) { list<menu> menus = new arraylist<menu>(); if ("allmenu".equals(params.getstring("allmenu"))) { menus = menudao.findlist(params); } else { // 通过用户查询角色 list<userrole> userroles = userroledao.findlist(params); // 通过角色查询菜单 list<rolemenu> rolemenus = new arraylist<rolemenu>(); if (userroles != null && userroles.size() > 0) { for (userrole userrole : userroles) { params = new dynamicparams(); if (userrole != null) { if (userrole.getroleid().equals(params.getstring("rid"))) { break; } params.put("roleid", userrole.getroleid().tostring()); list<rolemenu> rms = rolemenudao.findlist(params); for (rolemenu rolemenu : rms) { rolemenus.add(rolemenu); } } } } // 查询菜单信息 for (rolemenu rolemenu : rolemenus) { if (rolemenu != null) { menu menu = menudao.find(rolemenu.getmenuid()); if (menu != null) { menus.add(menu); } } } menus = removeduplicate(menus); collections.sort(menus); } return menus; }
/** * 去除菜单中重复项 * * @param list * @return */ private list<menu> removeduplicate(list<menu> list) { list<menu> result = new arraylist<menu>(); set<long> menuids = new hashset<long>(); for (int i = 0; i < list.size(); i++) { menu m = list.get(i); if (m != null && menuids.add(m.getid())) { result.add(m); } } return result; }
public list<rolemenu> findrolemenulist(dynamicparams params) { list<rolemenu> rolemenus = rolemenudao.findlist(params); return rolemenus; }
dao层
menudao
@override protected void createquery(dynamicparams params, stringbuffer sql, list<object> args) { sql.append("select s.* from sys_menu s where 1=1 "); string parentid = params.getstring("parentid"); if (stringutils.isnotblank(parentid)) { sql.append(" and parent_id = ? "); args.add(parentid); } string sort = params.getstring("sort"); string order = params.getstring("order"); if (stringutils.isnotblank(sort)) { sql.append(" order by ").append(hump2underline(sort)); if (stringutils.isnotblank(order)) { sql.append(" " + order); } else { sql.append(" desc "); } } else { sql.append("order by sort asc,id desc "); } }
userroledao
@override protected void createquery(dynamicparams params, stringbuffer sql, list<object> args) { sql.append("select s.* from sys_user_role s where 1=1 "); long adminid = params.getlong("adminid"); if (adminid != null) { sql.append(" and s.user_id = ?"); args.add(adminid); } }
rolemenudao
@override protected void createquery(dynamicparams params, stringbuffer sql, list<object> args) { sql.append("select s.* from ").append("sys_role_menu").append(" s where 1=1 "); long adminid = params.getlong("roleid"); if (adminid != null) { sql.append(" and s.role_id = ?"); args.add(adminid); } }
在web-inf目录下建立文件夹tlds 建立自定义标签文件shiros.tld,我们通过自定义标签实现页面按钮的控制。
<span style="color:#333333;"><?xml version="1.0" encoding="utf-8" ?> <taglib xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xsi:schemalocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd" version="2.0"> <description>p2p permission taglib</description> <display-name>permission taglib</display-name> <tlib-version>1.0</tlib-version> <short-name>p2p_back</short-name> <uri>http://vanfon.p2p.cn/</uri> <tag> <description>权限校验标签,有权限就显示标签体的内容,否则不显示</description> <name>permission</name> <tag-class>com.vanfon.p2p.back.tag.permissiontag</tag-class> <body-content>jsp</body-content> <attribute> <description></description> <name>module</name> <required>true</required> <rtexprvalue>false</rtexprvalue> </attribute> <attribute> <description></description> <name>code</name> <required>true</required> <rtexprvalue>false</rtexprvalue> </attribute> </tag> </taglib></span>
自定义标签类
package com.vanfon.p2p.back.tag; import java.util.list; import javax.servlet.http.httpservletrequest; import javax.servlet.jsp.jspexception; import javax.servlet.jsp.tagext.tagsupport; import com.vanfon.p2p.entity.system.admin; import com.vanfon.p2p.entity.system.menu; import com.vanfon.p2p.manager.system.authmanager; import com.vanfon.p2p.utils.dynamicparams; import com.vanfon.p2p.utils.springcontextholder; /** * 权限控制标签 * * @author zhangwx * @date 2015-2-5 */ public class permissiontag extends tagsupport { /** * */ private static final long serialversionuid = 4592227792811389132l; private string module;// 属性名必须与jsp自定义标签的属性名一样 private string code; public string getmodule() { return module; } public void setmodule(string module) { this.module = module; } public string getcode() { return code; } public void setcode(string code) { this.code = code; } @override public int dostarttag() throws jspexception { boolean result = false; httpservletrequest request = (httpservletrequest) this.pagecontext.getrequest();// 通过成员变量获取httpservletrequest对象 admin admin = (admin) request.getsession().getattribute("admin");// 获取登录到系统的用户 if (admin != null) { if ("1".equals(string.valueof(admin.getifsuper()))) {// 超级管理员 result = true; } else { dynamicparams params = new dynamicparams(); params.put("id", string.valueof(admin.getid())); params.put("module", this.module); params.put("code", this.code); authmanager authmanager = springcontextholder.getbean(authmanager.class); list<menu> userroleauths = authmanager.finduserroleauthlist(params); if (userroleauths != null && userroleauths.size() > 0) { result = true; } } } return result ? eval_body_include : skip_body; } }
以上就是该权限管理中权限树的大体实现,完成了java web实现用户权限管理的功能,希望对大家的学习有所帮助。