java web权限管理

数据库设计

我的设计如下:

用户:fu_admin

角色:sys_role

权限:sys_purview

用户-角色:sys_user_role

角色-权限:sys_role_purview

标准的权限管理系统设计为以上5张表。


注:用户、用户-角色我就不做说明了,这两个是很简单的两块,用户的crud,以及为用户分配角色(多对多的关系)稍微琢磨一下就清楚了,下面都是针对为角色分配权限的实现



后台实现

展示层采用ztree树

roleList.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 http-equiv="X-UA-Compatible" content="IE=Edge">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<%@ include file="../common/meta.jsp" %>
<%@ include file="/WEB-INF/include/tagtld.jsp"%>
<title>${title}-角色管理</title>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ include file="../common/cssback.jsp" %>
<style type="text/css">
.bg{
background-color:#808080;
} 
</style>
</head>
<body style="background:#fff">
<c:set var="first" value="7"/>
<c:set var="second" value="3"/>
<div class="content">
    <div class=" rt_cont">
    	<div class="rt_cont_mat">
    	    <div class="rt_cont_title">角色管理</div>            
            <div class=" yhlb_title">角色管理</div>
	            <div class="yhlb">
				
				<!-- 编辑栏  -->
				<div id="tb" style="padding:5px 5px;">
					<ul>
						<li style="float:left;margin-left:10px;"><domi:privilege url="/admin_op_purview/addRole.htm"><img src="../images/add.png"/><a href="javascript:void(0);" οnclick="addRole();">新增</a></domi:privilege></li>
						<li style="float:left;margin-left:10px;"><domi:privilege url="/admin_op_purview/editRole.htm"><img src="../images/edit.png"/><a href="javascript:void(0);" οnclick="editRole();">编辑</a></domi:privilege></li>
						<li style="float:left;margin-left:10px;"><domi:privilege url="/admin_op_purview/delRoleAjax.htm"><img src="../images/del.png"/><a href="javascript:void(0);" οnclick="delRole();">删除</a></domi:privilege></li>
						<li style="float:left;margin-left:10px;"><domi:privilege url="/admin_op_purview/setPurview.htm"><img src="../images/edit.png"/><a href="javascript:void(0);" οnclick="setMenu();">设置权限</a></domi:privilege></li>
					</ul>
				</div>
				
				<!-- 数据表格 -->
				<table width="100%" border="0" cellspacing="0" cellpadding="0">
					<tbody>
						<tr>
							<th> </th>
							<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>
						<c:forEach items="${roleList}" var="role" varStatus="row">
						<tr name="roleList">
							<input type="hidden" value="${role.id}"/>
							<td align="center" class="num" width="3%">${(row.index+1)}</td>
							<td field='name' sortable='true' width="10%">${role.roleName}</td>
							<td field='description' align='right' width="70%">${role.roleDesc}</td>
							<td field='createTimeFormat' align='center' width="17%"><fmt:formatDate value="${role.createTime}" pattern="yyyy-MM-dd HH:mm:ss"/></td>				
						</tr>
						</c:forEach>
					</tbody>
				</table>
	          </div>
            <div class="clr"></div> 
        </div>
    </div>
</div>
</body>
</html>
<script type="text/javaScript">
$("tr[name='roleList']").click(function(){
	$("tr[name='roleList']").removeClass();
  	$(this).addClass("bg");
});

function addRole(){
	$.fancybox.open({
          href : '${ctx}/admin_op_purview/addRole.htm',
          type : 'ajax',
          padding : 10
	});
}

function editRole(){
	var roleId=0;
	$("tr[name='roleList']").each(function(){
		if($(this).attr("class")=="bg"){
			roleId=$(this).children("input").val();
		}
	});
	if(roleId==0){
		jAlert("请选择角色!","提示",function(){
        });
        return null;
	}
	$.fancybox.open({
          href : '${ctx}/admin_op_purview/editRole.htm?roleId='+roleId,
          type : 'ajax',
          padding : 10
	});
}

function delRole(){
	var roleId=0;
	$("tr[name='roleList']").each(function(){
		if($(this).attr("class")=="bg"){
			roleId=$(this).children("input").val();
		}
	});
	if(roleId==0){
		jAlert("请选择角色!","提示",function(){
        });
        return null;
	}
	jConfirm("确认删除该角色?","操作提示",function(res){
		if(res){
			$.post('${ctx}/admin_op_purview/delRoleAjax.htm?roleId='+roleId,null,function(d){
				if(d==-1){
					jAlert("请先删除当前角色的下级角色","提示",function(){});
                	return null;
				}
				jAlert("角色删除成功","提示",function(){
					location.href=location.href;
        		});
			});
		}
	});
}


function setMenu(){
	var roleId=0;
	$("tr[name='roleList']").each(function(){
		if($(this).attr("class")=="bg"){
			roleId=$(this).children("input").val();
		}
	});
	if(roleId==0){
		jAlert("请选择角色!","提示",function(){
        });
        return null;
	}
	$.fancybox.open({
          href : '${ctx}/admin_op_purview/setPurview.htm?roleId='+roleId,
          type : 'ajax',
          padding : 10
	});
}
</script>



setPurview.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ include file="/WEB-INF/include/tagtld.jsp"%>
<div class="fuchen" style="width:500px;">
	<div class=" fc_top" style="width:500px;"> 
    	<b class="fl fc_top_font">配置权限</b>
        <div class="fl"></div>
    </div>
    <input id="roleId" type="hidden" value="${roleId}"/>
    <form id="roleForm">
	  	<!-- 权限窗口 -->  
	    <div id="menuDiv" title="配置权限" style="width:350px;padding:10px">  
	        <div id="tree" class="ztree" style="padding: 10px 20px;"></div>  
	    </div>  
	    <div id="menuWindowfooter" style="padding:5px;text-align:right;">   
	    	<a href="javascript:void(0);" οnclick="$.fancybox.close();" class="sure fl" style="width:80px;float:right;">取消</a> 
	        <domi:privilege url="/admin_op_purview/saveRolePurview.htm"><a href="javascript:void(0);" οnclick="ajaxSubmit()" class="sure fl" style="width:80px;float:right;">提交</a></domi:privilege> 
	    </div>  
	</form>
</div>

<script>
var globalId = null;
var setting = {
	async : {  
        enable : true, 
        url : "${ctx}/admin_op_purview/treedata.htm?roleId="+$("#roleId").val(),        
        autoParam : ["id", "name"]                    
    }, 
	check : {
		chkboxType:{"Y":"ps","N":"ps"},//勾选checkbox对于父子节点的关联关系,取消勾选时不关联父
		chkStyle:"checkbox",
		enable : true	//是否复选框
	},
	//数据
	data : {
		simpleData : {
			enable : true,
			idKey : "id",     
            pIdKey : "pId",
            rootPId: 0
		}
	},
	callback : {  
            onClick : function(event, treeId, treeNode, clickFlag) {  
                if(true) {
                	globalId = treeNode.id;
                }  
            },  
            //捕获异步加载出现异常错误的事件回调函数 和 成功的回调函数  
            onAsyncSuccess : function(event, treeId, treeNode, msg){  
            	
            }
        }  
};


$(function(){
	$.fn.zTree.init($("#tree"), setting);
	var treeObj = $.fn.zTree.getZTreeObj("tree");
	treeObj.expandAll(true);
});

//角色-菜单信息入库
function ajaxSubmit(){
	 var roleId = $("#roleId").val();
	 var treeObj=$.fn.zTree.getZTreeObj("tree");
     var nodes=treeObj.getCheckedNodes(true);
     var purviewArray = "";
     for(var i=0;i<nodes.length;i++){
    	//获取选中节点的值
    	 purviewArray = purviewArray + nodes[i].id + ",";
     }
     purviewArray=purviewArray.substring(0,purviewArray.length-1);
     jConfirm("您确定要修改当前角色的权限吗?","提示",function(res){
		if(res){
			$.post("${ctx}/admin_op_purview/saveRolePurview.htm",{"roleId":roleId,"purviewArray":purviewArray},function(data){
				jAlert("修改成功!","提示",function(){
					location.href=location.href;
        		});
			});
		}
	})
}

</script>


Action 层

AdminOpPurviewAction.java

  /**
	 * 设置权限页面
	 */
	@Action("setPurview")
	public String setPurview() {
		try {
			this.getActionContext().put("roleId", roleId);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}

	/**
	 * 权限树
	 * 
	 * @return
	 */
	@Action("treedata")
	public String treedata() {
		try {
			String jsonStr = sysRolePurviewService.findPurviewList(roleId);
			if (jsonStr == null) {
				jsonStr = "";
			}
			write(jsonStr);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

  /**
	 * 保存角色的菜单权限
	 */
	@Action("saveRolePurview")
	public String saveRolePurview() {
		try {
			sysRolePurviewService.saveRolePurview(roleId, purviewArray);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

service 层实现类

public String findPurviewList(Long roleId) {
		return sysRolePurviewDao.findPurviewList(roleId);
	}


	public void saveRolePurview(Long roleId, String purviewArray) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("roleId", roleId);
		List<SysRolePurview> list = sysRolePurviewDao.findList(map);
		if (list != null && list.size() > 0) {
			for (SysRolePurview sysRolePurview : list) {
				sysRolePurviewDao.delete(sysRolePurview.getId());// 先删除此角色的所有权限
			}
		}

		if (purviewArray != null && purviewArray != "") {
			String[] pArray = purviewArray.split(",");
			for (int i = 0; i < pArray.length; i++) {
				SysRolePurview rolePurview = new SysRolePurview();
				rolePurview.setSysPurview(sysPurviewDao.get(Long.parseLong(pArray[i])));
				rolePurview.setSysRole(sysRoleDao.get(roleId));
				sysRolePurviewDao.save(rolePurview);// 再给此角色配置选中的权限
			}
		}
	}

dao层实现类

@Repository
public class SysRolePurviewDaoImpl extends BaseDaoImpl<SysRolePurview, Long> implements SysRolePurviewDao {
	@Override  
    public List<SysRolePurview> findList(Map<String, Object> map) {  
		String hql=" from SysRolePurview where 1=1 ";
		List<Object> params=new ArrayList<Object>();
		if(map.containsKey("roleId")){
			params.add(map.get("roleId"));
			hql=hql+" and sysRole.id=? ";
		}
		if(map.containsKey("purviewId")){
			params.add(map.get("purviewId"));
			hql=hql+" and sysPurview.id=? ";
		}
		if(this.findAllByHQL(hql, params).size()>0){
			return this.findAllByHQL(hql, params);
		}else{
			return null;
		}
    }  
	
	@Override  
    public String findPurviewList(Long roleId) {  
		String sql="select id, name, parentid as pId from sys_purview where parentid is not null";
		List<Map<String, Object>> list = this.getJdbcTemplate().queryForList(sql);
		Map<String, Object> map=new HashMap<String, Object>();
		map.put("roleId", roleId);
		List<SysRolePurview> rolePv = this.findList(map);//根据角色id查询所拥有的权限
		JSONArray jsonArr = new JSONArray();
		for(Map<String, Object> purview : list){
			JSONObject obj = new JSONObject();
			obj.put("id", purview.get("id").toString());
			obj.put("name", purview.get("name").toString());
			obj.put("pId", purview.get("pId")!=null?purview.get("pId").toString():"");
			//如果在中间表有权限对应,则选中
			if(rolePv != null && rolePv.size()>0){
				for (SysRolePurview rolePurview : rolePv) {  
					String rpid = rolePurview.getSysPurview().getId().toString();
					String pid = purview.get("id").toString();
	            	//如果角色权限表的权限id跟权限表的id对应上,就选中
	                if (rpid.equals(pid)) {  
	                	obj.put("checked", true);  
	                } 
	            }  
			}
			jsonArr.add(obj);
		}
		return jsonArr.toString();
    }
	
}

这里吧权限表的实体列出来,其他的实体同理把双向多对一,一对多配置好


package com.hongwei.futures.model;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;

import org.hibernate.annotations.OrderBy;

@Entity
@Table(name = "sys_purview")
public class SysPurview implements java.io.Serializable{
	/**
	 * 
	 */
	private static final long serialVersionUID = 6386109543256527737L;
	private Long id;
	private String name;
	private Long parentId;
	private String url;
	private Integer type;
	private String iconicName;
	private Integer sort;
	private Integer category;
	private String remark;
	private String target;
	private FuAdmin createAdmin;
	private Date createTime;
	private FuAdmin updateAdmin;
	private Date updateTime;
	private Set<SysRolePurview> sysRolePurviews = new HashSet<SysRolePurview>(0);
	private Set<SysPurview> children = new HashSet<SysPurview>();//这里是用来存当前权限菜单下的子菜单
	
	
	public SysPurview() {
		super();
	}

	public SysPurview(Long id, String name, Long parentId, String url,
			Integer type, String iconicName, Integer sort, Integer category,
			String remark, String target, FuAdmin createAdmin, Date createTime,
			FuAdmin updateAdmin, Date updateTime, Set<SysPurview> children,Set<SysRolePurview> sysRolePurviews) {
		super();
		this.id = id;
		this.name = name;
		this.parentId = parentId;
		this.url = url;
		this.type = type;
		this.iconicName = iconicName;
		this.sort = sort;
		this.category = category;
		this.remark = remark;
		this.target = target;
		this.createAdmin = createAdmin;
		this.createTime = createTime;
		this.updateAdmin = updateAdmin;
		this.updateTime = updateTime;
		this.sysRolePurviews = sysRolePurviews;
		this.children = children;
	}

	@Id
	@GeneratedValue
	@Column(name = "id", unique = true, nullable = false)
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}

	@Column(name = "name")
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Column(name = "parentid")
	public Long getParentId() {
		return parentId;
	}

	public void setParentId(Long parentId) {
		this.parentId = parentId;
	}

	@Column(name = "url")
	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	@Column(name = "type")
	public Integer getType() {
		return type;
	}

	public void setType(Integer type) {
		this.type = type;
	}

	@Column(name = "iconicname")
	public String getIconicName() {
		return iconicName;
	}

	public void setIconicName(String iconicName) {
		this.iconicName = iconicName;
	}

	@Column(name = "sort")
	public Integer getSort() {
		return sort;
	}

	public void setSort(Integer sort) {
		this.sort = sort;
	}

	@Column(name = "category")
	public Integer getCategory() {
		return category;
	}

	public void setCategory(Integer category) {
		this.category = category;
	}

	@Column(name = "remark")
	public String getRemark() {
		return remark;
	}

	public void setRemark(String remark) {
		this.remark = remark;
	}

	@Column(name = "target")
	public String getTarget() {
		return target;
	}

	public void setTarget(String target) {
		this.target = target;
	}

	@ManyToOne(fetch = FetchType.LAZY)
	@JoinColumn(name = "createadmin")
	public FuAdmin getCreateAdmin() {
		return createAdmin;
	}
	public void setCreateAdmin(FuAdmin createAdmin) {
		this.createAdmin = createAdmin;
	}

	@Column(name = "createtime")
	public Date getCreateTime() {
		return createTime;
	}

	public void setCreateTime(Date createTime) {
		this.createTime = createTime;
	}

	@ManyToOne(fetch = FetchType.LAZY)
	@JoinColumn(name = "updateadmin")
	public FuAdmin getUpdateAdmin() {
		return updateAdmin;
	}
	public void setUpdateAdmin(FuAdmin updateAdmin) {
		this.updateAdmin = updateAdmin;
	}

	@Column(name = "updatetime")
	public Date getUpdateTime() {
		return updateTime;
	}

	public void setUpdateTime(Date updateTime) {
		this.updateTime = updateTime;
	}

	@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "sysRole")
	public Set<SysRolePurview> getSysRolePurviews() {
		return sysRolePurviews;
	}

	public void setSysRolePurviews(Set<SysRolePurview> sysRolePurviews) {
		this.sysRolePurviews = sysRolePurviews;
	}
	
	@OneToMany(fetch=FetchType.EAGER, mappedBy="parentId")
	@OrderBy(clause = "id ASC")
	public Set<SysPurview> getChildren() {
		return children;
	}

	public void setChildren(Set<SysPurview> children) {
		this.children = children;
	}
	
}


在WEB-INF目录下建立文件夹tld 建立自定义标签文件domi.tld,我们通过自定义标签实现页面按钮的控制。

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
                        "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
	<tlib-version>1.0</tlib-version>
	<jsp-version>1.2</jsp-version>
	<short-name>sapTag</short-name>
	<uri>http://www.hongwei.com</uri>

	<tag>
		<name>privilege</name>
		<tag-class>com.hongwei.futures.web.tag.PrivilegeTag</tag-class>
		<body-content>JSP</body-content>
		<attribute>
			<name>url</name>
			<required>true</required>
			<rtexprvalue>true</rtexprvalue>
			<description>url</description>
		</attribute>
	</tag>
	<tag>
		<name>menu</name>
		<tag-class>com.hongwei.futures.web.tag.MenuTag</tag-class>
		<body-content>JSP</body-content>
		<attribute>
			<name>name</name>
			<required>true</required>
			<rtexprvalue>true</rtexprvalue>
			<description>name</description>
		</attribute>
	</tag>
</taglib>

自定义标签类(两个,一个用来在后台主页循环菜单,一个用来判断按钮权限)

package com.hongwei.futures.web.tag;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.servlet.jsp.tagext.TagSupport;

import com.hongwei.futures.model.FuAdmin;
import com.hongwei.futures.model.SysPurview;
import com.hongwei.futures.util.StrutsUtil;

public class PrivilegeTag extends TagSupport {

	private String url;

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	@Override
	public int doStartTag() {
		boolean result = false;
		FuAdmin admin = (FuAdmin) StrutsUtil.getHttpSession().getAttribute("admin");
		List<SysPurview> priviList = (List<SysPurview>) StrutsUtil.getHttpSession().getAttribute("priviList");
		if (null != admin) {
			if (admin.getType() == 1) {
				result = true;
			} else {
				int pos = url.indexOf("?");
				if (pos > -1) {
					url = url.substring(0, pos);
				}
				Collection<String> privilegeUrls = new ArrayList<String>();
				for (SysPurview p : priviList) {
					privilegeUrls.add(p.getUrl());
				}
				if (!privilegeUrls.contains(url)) {

				} else {
					for (String pUrl : privilegeUrls) {
						if (url.equals(pUrl)) {
							result = true;
						}
					}
				}
			}
		}
		return result ? EVAL_BODY_INCLUDE : SKIP_BODY;
	}
}

package com.hongwei.futures.web.tag;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.servlet.jsp.tagext.TagSupport;

import com.hongwei.futures.model.FuAdmin;
import com.hongwei.futures.model.SysPurview;
import com.hongwei.futures.util.StrutsUtil;


public class MenuTag extends TagSupport{
	
	private String name;
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Override
	public int doStartTag(){
		boolean result = false;  
		FuAdmin admin = (FuAdmin) StrutsUtil.getHttpSession().getAttribute("admin");
		if(admin.getType()==1){
			result = true;
		}else{
			Collection<String> privilegeNames = new ArrayList<String>();
			List<SysPurview> priviList = (List<SysPurview>) StrutsUtil.getHttpSession().getAttribute("priviList");
			if(priviList != null && priviList.size()!=0){
				for(SysPurview p:priviList){
					privilegeNames.add(p.getName());
				}
				if (!privilegeNames.contains(name)) {
					
				} else {
					for(String pName:privilegeNames){
						if(name.equals(pName)){
							result = true;
						}
					}
				}
			}
		}
        return result ? EVAL_BODY_INCLUDE : SKIP_BODY;  
	}
}

后台主页

indexHome.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 http-equiv="X-UA-Compatible" content="IE=Edge">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<%@ include file="../common/meta.jsp" %>
<%@ include file="/WEB-INF/include/tagtld.jsp"%>
<title>${title}-后台管理</title>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@include file="../common/cssback.jsp" %>
<style>
	.newgiude_icont{margin: 15px 10px 0 !important;}
	.lf_nav_title{font-size:17px;}
	.lf_nav_small{ border-left: 5px solid #efefef;border-bottom: 1px solid #fff;box-shadow: 1px 1px #fff;-moz-box-shadow:1px 1px #fff; -webkit-box-shadow:1px 1px #fff;display: block;height: 50px;text-indent: 22px;line-height:50px;}
	.newg_icont{display: block;width:19px;height:11px;background: url("../images_hhr/helpUp.png") no-repeat center;float: right;margin: 5px 53px;cursor: pointer;}
	.lf_smallNav{display:none;}
	.lf_nav{height:auto !important;}
	.frame{float:right;width:100%;height:100%;}
	.lf_nav ul li{border-bottom: 1px solid #fff;box-shadow: 1px 1px #fff;-moz-box-shadow:1px 1px #fff; -webkit-box-shadow:1px 1px #fff;}
	</style>
</head>
<body>
<c:if test="${empty admin}">
<c:redirect url="${ctx}/admin_login/adminLogin.htm"></c:redirect>
</c:if>
<div class="top">
<div class=" top_title fl">后台管理</div>
    <div class="fr grzx"><span class="geren">您好,${admin.account}  [${roleName}]</span>    <a href="javascript:void(0);" οnclick="changeIframe('${ctx}/admin_list_user/editPasswordAjax.htm')" class="tuichu">修改密码</a><span class="shuxian">|</span><c:if test="${admin.account != null}"><a href="javascript:void(0);" οnclick="logout();" class="tuichu">退出</a></c:if></div>
    <div class="clr"></div>
</div>
<div class="content">
	<div class="lf_nav" style="z-index:999;">
		<s:iterator value="#application.topPrivilegeList">
 			<domi:menu name="${name}">
 				<li class="lf_nav_title" value="1"><a class="lf_nav_small" href="javascript:vodi(0);" ><b>${name}</b><em class="newgiude_icont"></em></a></li>
			</domi:menu>
 			
 				<ul class="lf_smallNav">
	 			<s:iterator value="children" status="row">
	  				<domi:menu name="${name}">
						<li name="urli"><a target="iframepage"  href="javascript:void(0);" οnclick="changeIframe('${ctx}${url}')"><i></i>${name}<!-- <span style="color:red;" id="message"></span> --></a></li>
					</domi:menu>
	  			</s:iterator>
  				</ul>
 		</s:iterator>
    </div>
    <div class="frame"><iframe class="video" src="${ctx}/admin_login/welcome.htm" frameborder=0  marginwidth=0 marginheight=0 hspace=0 vspace=0  scrolling=no width="100%" height=100% id="iframepage" name="iframepage" onLoad="iFrameHeight()"  ></iframe></div>
</div>
</body>
</html>
<script type="text/javascript">
	$("li[name='urli']").click(function(){
	$("li[name='urli']").removeClass();
  	$(this).addClass("yxz");
	});

	function logout(){
		$.post("${ctx}/admin_login/logoutAjax.htm",null,function(date){
			if(date == "-1"){
				location.href="${ctx}/admin_login/adminLogin.htm";
			}else if(date == "-2"){
				sureInfo("确定","请您先登录","提示");
				location.href="${ctx}/admin_login/adminLogin.htm";
			}
		});
	};
	
	//iframe自适应高度
	  function iFrameHeight() {
        	var ifm= document.getElementById("iframepage");
        	var subWeb = document.frames ? document.frames["iframepage"].document :ifm.contentDocument;
            if(ifm != null && subWeb != null) {
            	ifm.height = subWeb.body.scrollHeight;
            }
    };
    
    //iframe右边页面跳转,参照最后一个li
	  function changeIframe(url){
        var urlValue = url;
        document.getElementById("iframepage").src = urlValue;
    }
    
	 $(document).ready(function(){
	 //导航栏折叠
		 $(".lf_nav .lf_nav_title").click(function(){
             $(this).find("em").toggleClass("newg_icont");
             $(this).next().toggle();
             var index = $(".lf_nav .lf_nav_title").index(this);
             $(".lf_nav .lf_nav_title").each(function(i){
                 if(i != index){
                     if($(this).next().css("display")=="block"){
                     	$(this).find("em").toggleClass("newg_icont");
                         $(this).next().css("display","none");
                     }
                 }
             });
         });
	});
	
</script>


拦截器

package com.hongwei.futures.web.interceptor;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;

import com.hongwei.futures.model.FuAdmin;
import com.hongwei.futures.model.SysPurview;
import com.hongwei.futures.model.SysRole;
import com.hongwei.futures.service.FuAdminService;
import com.hongwei.futures.service.SysRolePurviewService;
import com.hongwei.futures.service.SysRoleService;
import com.hongwei.futures.util.WebUtil;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class PurviewInterceptor extends AbstractInterceptor {

	private static final long serialVersionUID = -5615631164011209571L;

	@Autowired
	public FuAdminService fuAdminService;
	@Autowired
	private SysRoleService sysRoleService;
	@Autowired
	private SysRolePurviewService sysRolePurviewService;

	@SuppressWarnings("unchecked")
	public String intercept(ActionInvocation ai) throws Exception {
		String namespace = ai.getProxy().getNamespace();
		String actionName = ai.getProxy().getActionName();
		String privUrl = namespace + "/" + actionName;

		FuAdmin fuAdmin = null;
		if (WebUtil.getCookieByName(ServletActionContext.getRequest(), "admin_token") != null) {// 自动登录
			String token = WebUtil.getCookieByName(ServletActionContext.getRequest(), "admin_token");
			fuAdmin = fuAdminService.findLoginByToken(token);
			if (null == fuAdmin) {// 跳转登录页面
				if (privUrl.startsWith("/admin_login/adminLogin")) { // 登录的URL
					return ai.invoke();
				} else if (privUrl.startsWith("/admin_login/adminForward")) {
					return ai.invoke();
				} else {
					return WebUtil.returnCode(ai, "reAdminLogin");
				}
			} else {
				ai.getInvocationContext().getValueStack().setValue("admin", fuAdmin);
				ai.getInvocationContext().getValueStack().setValue("adminId", fuAdmin.getId());
				if (privUrl.startsWith("/admin_login/adminForward")) {
					return ai.invoke();
				}
				if (privUrl.startsWith("/admin_login/indexHome")) {
					return ai.invoke();
				}
				if (privUrl.startsWith("/admin_login/logoutAjax")) {
					return ai.invoke();
				}
				privUrl = privUrl + ".htm";
				boolean result = false;
				List<SysPurview> priviList = (List<SysPurview>) ActionContext.getContext().getSession().get("priviList");
				if (null == priviList) { // sesson过期
					// 重新存储用户对应的角色权限 和用户对象
					List<SysRole> roleList = sysRoleService.findRoleListByRoleId(fuAdmin.getId());
					for (SysRole role : roleList) {
						priviList = sysRolePurviewService.findPurviewListByRoleId(role.getId());
					}
					ActionContext.getContext().getSession().put("priviList", priviList);
					ActionContext.getContext().getSession().put("admin", fuAdmin);
					// return WebUtil.returnCode(ai, "nopermission");// 没有权限的页面
				}
				if (fuAdmin.getType() == 1) { // 超管
					result = true;
				} else {
					int pos = privUrl.indexOf("?");
					if (pos > -1) {
						privUrl = privUrl.substring(0, pos);
					}
					Collection<String> privilegeUrls = new ArrayList<String>();

					for (SysPurview p : priviList) {
						privilegeUrls.add(p.getUrl());
					}
					if (!privilegeUrls.contains(privUrl)) {

					} else {
						for (String pUrl : privilegeUrls) {
							if (privUrl.equals(pUrl)) {
								result = true;
							}
						}
					}
				}
				if (result == true) {
					return ai.invoke();
				} else {
					return WebUtil.returnCode(ai, "nopermission");// 没有权限的页面
				}
			}
		} else {
			return WebUtil.returnCode(ai, "reAdminLogin");
		}
	}

}

拦截器配置文件struts.xml

<package name="admin" extends="control-center">
		<interceptors>		
			<interceptor name="checkPurviewInterceptor" class="com.hongwei.futures.web.interceptor.PurviewInterceptor"></interceptor>
			
			<interceptor-stack name="defaultStack">
				<interceptor-ref name="checkPurviewInterceptor"></interceptor-ref>
				<interceptor-ref name="defaultStack"></interceptor-ref>
			</interceptor-stack>
		</interceptors>
</package>

监听器,用来加载后台所有权限菜单(顶级菜单,子菜单两个集合)

package com.hongwei.futures.web.listener;

import java.util.Collection;
import java.util.List;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.hongwei.futures.model.SysPurview;
import com.hongwei.futures.service.SysPurviewService;

public class InitListener implements ServletContextListener{
	
	
	// 装载权限列表的URL数据
	public void contextInitialized(ServletContextEvent sc) {
		ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(sc.getServletContext());
		SysPurviewService sysPurviewService = (SysPurviewService) ac.getBean("sysPurviewServiceImpl");
		
		List<SysPurview> purviewList = sysPurviewService.findTopPrivilege();
		sc.getServletContext().setAttribute("topPrivilegeList", purviewList);
		System.out.println("------------> 已准备数据topPrivilegeList <------------");
		
		// 准备数据:allPrivilegeUrls
		Collection<String> allPrivilegeUrls = sysPurviewService.getAllPrivilegeUrls();
		sc.getServletContext().setAttribute("allPrivilegeUrls", allPrivilegeUrls);
		System.out.println("------------> 已准备数据allPrivilegeUrls <------------");
	}

	public void contextDestroyed(ServletContextEvent arg0) {
		
	}
}

监听配置web.xml

       <listener>
		<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
	</listener>
	
	<listener>
		<listener-class>com.hongwei.futures.web.listener.InitListener</listener-class>
	</listener>

以上就是该权限管理中权限树(为角色分配权限)的大体实现,下面是效果图





评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值