攔截器(Interceptor):攔截器是Struts2的核心,Struts2的眾多功能都是通過攔截器來實(shí)現(xiàn)的。
攔截器跟filter的概念是非常類似的,攔截器只能攔截Action的,而filter是可以過濾所有的東西的.An interceptor is a stateless class that follows the interceptor pattern, as found inFilter
and in AOP languages.
Interceptors must be stateless(無狀態(tài)的) and not assume that a new instance will be created for each request or Action是單實(shí)例的,
攔截器的編寫有兩步,一個(gè)是編寫代碼,第二個(gè)是編寫配置文件.
自定義的攔截器要實(shí)現(xiàn)Interceptor接口ActionInvocation的invoke方法就類似于filter的dofilter
配置文件中用<interceptors>中進(jìn)行配置.注意攔截器的init方法也是在服務(wù)器一啟動(dòng)的時(shí)候就調(diào)用的,跟filter一樣的.整個(gè)struts都是靠這些攔截器所串聯(lián)起來的.我們并沒有在action里面配置也沒問題啊,因?yàn)樗袀€(gè)默認(rèn)的攔截器棧嘛.是通過 <default-interceptor-ref name="defaultStack"/>來指定的.
注意:一旦定義了自己的攔截器,將其配置到action上后,我們需要在action的最后加上默認(rèn)的攔截器棧:defaultStack。因?yàn)樽约旱臅?huì)覆蓋默認(rèn)的.
攔截器也可以跟filter一樣配置param,然后在程序里面可以把它讀出來.在程序中它用setter方法set進(jìn)去的.
如:
<interceptor name="theInterceptor1" class="cn.wenping.interceptor.TheInterceptor1">
<param name="test">wenp</param>
</interceptor>
攔截器定義如下:
public class TheInterceptor1 implements Interceptor {
private String test;
public String getTest() {
return test;
}
public void setTest(String test) {
this.test = test;
}
.............
..............
}
定義攔截器時(shí)可以直接繼承AbstractInterceptor抽象類(該類實(shí)現(xiàn)了Interceptor接口,并且對(duì)init和destroy方法進(jìn)行了空實(shí)現(xiàn)),然后實(shí)現(xiàn)其抽象方法intercept即可,實(shí)際上就是一個(gè)適配器
注意:以上說的過濾Action實(shí)際上是過濾他的execute方法,如果要對(duì)指定的方法進(jìn)行攔截用:MethodFilterInterceptor,此即方法過濾攔截器(可以對(duì)指定方法進(jìn)行攔截的攔截器)。
采用的是下面兩種param進(jìn)行配置
- excludeMethods - method names to be excluded from interceptor processing
- includeMethods - method names to be included in interceptor processing
配置如下:如果用如下配置,那么myExecute方法在Action中要進(jìn)行method方法的配置
<interceptor-ref name="theInterceptor3">
<param name="includeMethods">myExecute</param>
</interceptor-ref>
注意:在方法過濾攔截器中,如果既沒有指定includeMethods參數(shù),也沒有指定execludeMethods參數(shù),那么所有的方法都會(huì)被攔截,也就是說所有的方法都被認(rèn)為是includeMethods的;如果僅僅指定了includeMethods,那么只會(huì)攔截includeMethods中的方法,沒有包含在includeMethods中的方法就不會(huì)被攔截。
關(guān)于攔截器中的監(jiān)聽器:
ActionInvocation中的方法:addPreResultListener
PreResultListeners may be registered with anActionInvocation
to get a callback after theAction
has been executed but before theResult
is executed.
他起的作用就是:如果你想在Action的方法執(zhí)行完畢之后在結(jié)果返回之前想要做點(diǎn)東西的話就可以用它們.