struts2根据拦截器实现链接的权限管理

阅读更多
首先在struts.xml的配置中添加拦截器



	
	
	
	
	
		
			
		
		
			
			
				
				
			
		
		
		
			/index.jsp
		......

然后是拦截器类:
package com.gd.interceptor;

import java.util.Map;

import javax.servlet.ServletContext;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.gd.po.Userinfo;
import com.gd.service.ISecurityPermissionManager;
import com.gd.service.ISecurityUserManager;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class AdminInterceptor extends AbstractInterceptor {
	
	private static final long serialVersionUID = 7426957840297915277L;
	@Override
	public String intercept(ActionInvocation ai) throws Exception {
		Map session = ai.getInvocationContext().getSession();
		if (session == null) {
			return Action.LOGIN;
		}
		Userinfo user = (Userinfo) session.get("user");
		if (user == null) {
			session.put("message", "请先登录!");
			return Action.LOGIN;
		}
		
		// 用户访问Action权限判断
		if (!actionAuthority(ai, session)) {
			return Action.LOGIN;
		}

		return ai.invoke();
	}
	public boolean actionAuthority(ActionInvocation ai, Map session) {
		// 用户访问Action权限判断
		ServletContext sc = ServletActionContext.getServletContext();
                //此处获取请求的action及其方法
		String permission = ai.getProxy().getActionName().toLowerCase() + "." + ai.getProxy().getMethod().toLowerCase();
		ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(sc);
		ISecurityUserManager securityUserManager = (ISecurityUserManager) context.getBean("securityUserManager");
		ISecurityPermissionManager securityPermissionManager = (ISecurityPermissionManager) context.getBean("securityPermissionManager");
                //查询数据库是否有相同的链接有相同的则有权限访问
		if(!securityPermissionManager.checkIsRepeatPermission(permission)){
			return true;
		}
		if(securityUserManager!=null){
			Userinfo userInfo=(Userinfo)session.get("user");
			return securityUserManager.checkPrivilege(userInfo.getUserName(),permission);
		}
		return true;
	}
}

你可能感兴趣的:(struts2根据拦截器实现链接的权限管理)