Struts2的拦截器是个好利器!尤其是自定义拦截器,以下是我个人整理的很详细的整个流程,希望给大家带来帮助,有更好见解的希望可以提出宝贵的意见。
原理:
a) Web浏览器发送请求
b) 首先通过一组Struts2默认的拦截栈 dispatcher (或者 ServletFilter)
c) 自定义interceptor(拦截器)
d) Action
e) Result
struts.xml配置如下:
/error.jsp
/error.jsp
IndexAction
testAction
Success.jsp
input.jsp
annoction注解中使用拦截器和拦截栈
//直接在类名称的上端写入即可,value中指定要引入的拦截器的名称即可
@InterceptorRef(value="token")//拦截栈的引用,蓝色字体即拦截栈的引用名称
@InterceptorRefs(@InterceptorRef("sessionCheckStack"))
自定义拦截器的javabean
packagecom.cqrcb.perinvite.interceptor;importcom.cqrcb.perinvite.logon.action.IndexAction;importcom.netbank.pub.vo.core.PbClientInfoVO;importcom.opensymphony.xwork2.ActionContext;importcom.opensymphony.xwork2.ActionInvocation;importcom.opensymphony.xwork2.interceptor.AbstractInterceptor;/*** 权限拦截Action
*@authorwangyupeng
**/
//继承 AbstractInterceptor 类
public class AuthorityInterceptor extendsAbstractInterceptor{private static final long serialVersionUID = 4546936882066035745L;//重写intercept方法
public String intercept(ActionInvocation invocation) throwsException {//获取Action的拦截路径
ActionContext ax =invocation.getInvocationContext();//获取Action对象
Object action =invocation.getAction();//对IndexAction不做该项拦截 action instanceof IndexAction 解释为如果Action的实例为IndexAction
if (action instanceofIndexAction) {//如果是IndexAction,则进行执行,即不做拦截
returninvocation.invoke();
}//获取session中key为pinfo的对象
PbClientInfoVO pinfo =(PbClientInfoVO) ax.getSession().get("pinfo");if(pinfo==null){//如果pinfo为null,则返回全局result为backhone的视图
return "backhome";
}//如果都不为false,则不做拦截
returninvocation.invoke();
}
}
struts2的自定义拦截器有很多方式,本文的内容是前置拦截,即获取到action的请求所做的拦截。struts2还有后置拦截和中间拦截,这两种也是很常用的,有时间整理完之后我会发到博客,大家一起探讨。
原文:http://www.cnblogs.com/anhelida/p/3963146.html