转自:http://www.blogjava.net/i369/articles/162407.html
如何使用struts2拦截器,或者自定义拦截器。特别注意,在使用拦截器的时候,在Action里面必须最后一定要引用struts2自带的拦截器缺省堆栈defaultStack,如下(这里我是引用了struts2自带的checkbox拦截器):
每一个拦截器都可以配置参数,有两种方式配置参数,一是针对每一个拦截器定义参数,二是针对一个拦截器堆栈统一定义所有的参数,例如:
或者
每一个拦截器都有两个默认的参数:
excludeMethods - 过滤掉不使用拦截器的方法和
includeMethods – 使用拦截器的方法。
需要说明的几点:
1 拦截器执行的顺序按照定义的顺序执行,例如:
的执行顺序为:
thisWillRunFirstInterceptor
thisWillRunNextInterceptor
followedByThisInterceptor
thisWillRunLastInterceptor
MyAction1
MyAction2 (chain)
MyPreResultListener
MyResult (result)
thisWillRunLastInterceptor
followedByThisInterceptor
thisWillRunNextInterceptor
thisWillRunFirstInterceptor
2 使用默认拦截器配置每个Action都需要的拦截器堆栈,例如:
可以按照如下的方式定义:
3 如何访问HttpServletRequest,HttpServletResponse或者HttpSession
有两种方法可以达到效果,使用ActionContext:
Map attibutes = ActionContext.getContext().getSession();
或者实现相应的接口:
HttpSession SessionAware
HttpServletRequest ServletRequestAware
HttpServletResponse ServletResponseAware