Struts2拦截器配置

Struts 拦截器配置

1、新建拦截器,该拦截器用于拦截方法并继承MethodFilterInterceptor,重写doIntercept方法:

package com.current.interceptor;

import java.util.List;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import com.current.pagemodel.User;
import com.current.util.RequestUtil;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;

public class AuthInterceptor extends MethodFilterInterceptor{
	private static final Logger logger = Logger
			.getLogger(AuthInterceptor.class);

	private static final long serialVersionUID = 1L;

	@Override
	protected String doIntercept(ActionInvocation actionInvocation) throws Exception {
		logger.info("执行这里");
		ActionContext act = actionInvocation.getInvocationContext();
		//取到Sessoin对象
		User sessioninfo = (User) ActionContext.getContext().getSession().get("User");
		if(sessioninfo.getUsername().equals("admin")){//如果是管理员不需要验证权限
			return actionInvocation.invoke();
		}
		//得到请求的地址
		String requestPath = RequestUtil.getRequestPath(ServletActionContext.getRequest());
		logger.info("拦截的方法类:"+actionInvocation.getAction().getClass());
		logger.info("请求的方法:"+requestPath);
		List<String> auths = sessioninfo.getResourceUrls();
		if(auths!=null &&auths.size()>0){
			if(auths.contains(requestPath)){
				return actionInvocation.invoke();
			}else{
				logger.info("测试测试");
				ServletActionContext.getRequest().setAttribute("msg", 
						"您没有访问此资源的权限!<br/>请联系超管赋予您<br/>[" + requestPath + "]<br/>的资源访问权限!"
						);
				return "noAuth";
			}
		}
		logger.info(ServletActionContext.getRequest().getAttribute("msg"));
		return "noAuth";
	}

}

 该拦截器主要是从用户Session中获取用户的权限,前台页面根据权限控制用户所能访问的资源。

 

2、在Struts.xml中配置拦截器

<package name="basePackage" extends="struts-default">
	<!-- 配置拦截器 -->
	<interceptors>
		<interceptor name="authInterceptor" class="com.current.interceptor.AuthInterceptor"/>
		<!-- 配置拦截栈 -->
		<interceptor-stack name="authStack">
			<interceptor-ref name="authInterceptor">
			<!-- 指定拦截器不需要过滤的方法 -->
				<param name="excludeMethods">
					login,getTreeNode
				</param>
			</interceptor-ref>
			<!-- 默认拦截栈 ,如果不配置后台有可能获取不到前台表单的值 -->
			<interceptor-ref name="defaultStack"></interceptor-ref>
		</interceptor-stack>
	</interceptors>
	<default-interceptor-ref name="authStack"></default-interceptor-ref>
	<global-results>
		<result name="noAuth">/error/noAuth.jsp</result>
	</global-results>	
		<action name="acceptDLAction" class="com.current.action.ChainingAction" method="acceptDLAction">  
	  	<result name="success" type="plainText">
	  	<param name="charSet">UTF-8</param>
	  	<param name="location">/MyJsp.jsp</param>
	  	</result>  
	  	</action>  
	</package>

 

你可能感兴趣的:(struts2拦截器)