攔截器,攔截器棧總結

尊重原創  傳送門先行:   http://blog.csdn.net/yjsuge/article/details/6661391


攔截器(Interceptor):攔截器是Struts2的核心,Struts2的衆多功能都是通過攔截器來實現的。

攔截器跟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(無狀態的) and not assume that a new instance will be created for each request or Action是單實例的,

攔截器的編寫有兩步,一個是編寫代碼,第二個是編寫配置文件.

自定義的攔截器要實現Interceptor接口ActionInvocation的invoke方法就類似於filter的dofilter

配置文件中用<interceptors>中進行配置.注意攔截器的init方法也是在服務器一啓動的時候就調用的,跟filter一樣的.整個struts都是靠這些攔截器所串聯起來的.我們並沒有在action裏面配置也沒問題啊,因爲他有個默認的攔截器棧嘛.是通過 <default-interceptor-ref name="defaultStack"/>來指定的.

注意:一旦定義了自己的攔截器,將其配置到action上後,我們需要在action的最後加上默認的攔截器棧:defaultStack。因爲自己的會覆蓋默認的.

攔截器也可以跟filter一樣配置param,然後在程序裏面可以把它讀出來.在程序中它用setter方法set進去的.

如:

<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;
}

.............

..............

}

定義攔截器時可以直接繼承AbstractInterceptor抽象類(該類實現了Interceptor接口,並且對init和destroy方法進行了空實現),然後實現其抽象方法intercept即可,實際上就是一個適配器

注意:以上說的過濾Action實際上是過濾他的execute方法,如果要對指定的方法進行攔截用:MethodFilterInterceptor,此即方法過濾攔截器(可以對指定方法進行攔截的攔截器)。

採用的是下面兩種param進行配置

  • excludeMethods - method names to be excluded from interceptor processing
  • includeMethods - method names to be included in interceptor processing  
配置如下:如果用如下配置,那麼myExecute方法在Action中要進行method方法的配置

<interceptor-ref name="theInterceptor3">
<param name="includeMethods">myExecute</param>
</interceptor-ref>

注意:在方法過濾攔截器中,如果既沒有指定includeMethods參數,也沒有指定execludeMethods參數,那麼所有的方法都會被攔截,也就是說所有的方法都被認爲是includeMethods的;如果僅僅指定了includeMethods,那麼只會攔截includeMethods中的方法,沒有包含在includeMethods中的方法就不會被攔截。


關於攔截器中的監聽器:

ActionInvocation中的方法:addPreResultListener

PreResultListeners may be registered with anActionInvocation to get a callback after theAction has been executed but before theResult is executed.

他起的作用就是:如果你想在Action的方法執行完畢之後在結果返回之前想要做點東西的話就可以用它們.


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章