在之前的文章中,我們已經(jīng)涉及到了攔截器(Interceptor)的概念。
downpour 寫(xiě)道
攔截器是AOP中的概念,它本身是一段代碼,可以通過(guò)定義“織入點(diǎn)”,來(lái)指定攔截器的代碼在“織入點(diǎn)”的前后執(zhí)行,從而起到攔截的作用。正如上面 Struts2的Reference中講述的,Struts2的Interceptor,其攔截的對(duì)象是Action代碼,可以定義在Action代碼之前或者之后執(zhí)行攔截器的代碼。
接下來(lái),我們將重點(diǎn)討論一下Struts2中的攔截器的內(nèi)部結(jié)構(gòu)和執(zhí)行順序,并結(jié)合源碼進(jìn)行分析。
讓我們?cè)賮?lái)回顧一下之前我們?cè)?jīng)用過(guò)的一張Action LifeCycle的圖:
圖中,我們可以發(fā)現(xiàn),Struts2的Interceptor一層一層,把Action包裹在最里面。這樣的結(jié)構(gòu),大概有以下一些特點(diǎn):
1. 整個(gè)結(jié)構(gòu)就如同一個(gè)堆棧,除了Action以外,堆棧中的其他元素是Interceptor 2. Action位于堆棧的底部。由于堆棧"先進(jìn)后出"的特性,如果我們?cè)噲D把Action拿出來(lái)執(zhí)行,我們必須首先把位于Action上端的Interceptor拿出來(lái)執(zhí)行。這樣,整個(gè)執(zhí)行就形成了一個(gè)遞歸調(diào)用 3. 每個(gè)位于堆棧中的Interceptor,除了需要完成它自身的邏輯,還需要完成一個(gè)特殊的執(zhí)行職責(zé)。這個(gè)執(zhí)行職責(zé)有3種選擇:
1) 中止整個(gè)執(zhí)行,直接返回一個(gè)字符串作為resultCode
2) 通過(guò)遞歸調(diào)用負(fù)責(zé)調(diào)用堆棧中下一個(gè)Interceptor的執(zhí)行
3) 如果在堆棧內(nèi)已經(jīng)不存在任何的Interceptor,調(diào)用Action
Struts2的攔截器結(jié)構(gòu)的設(shè)計(jì),實(shí)際上是一個(gè)典型的
責(zé)任鏈模式的應(yīng)用。首先將整個(gè)執(zhí)行劃分成若干相同類(lèi)型的元素,每個(gè)元素具備不同的邏輯責(zé)任,并將他們納入到一個(gè)鏈?zhǔn)降臄?shù)據(jù)結(jié)構(gòu)中(我們可以把堆棧結(jié)構(gòu)也看作是一個(gè)遞歸的鏈?zhǔn)浇Y(jié)構(gòu)),而每個(gè)元素又有責(zé)任負(fù)責(zé)鏈?zhǔn)浇Y(jié)構(gòu)中下一個(gè)元素的執(zhí)行調(diào)用。
這樣的設(shè)計(jì),從代碼重構(gòu)的角度來(lái)看,實(shí)際上是將一個(gè)復(fù)雜的系統(tǒng),分而治之,從而使得每個(gè)部分的邏輯能夠高度重用并具備高度可擴(kuò)展性。所以,Interceptor結(jié)構(gòu)實(shí)在是Struts2/Xwork設(shè)計(jì)中的精華之筆。
Interceptor的定義 我們來(lái)看一下Interceptor的接口的定義:
- public interface Interceptor extends Serializable {
-
-
-
-
- void destroy();
-
-
-
-
-
-
- void init();
-
-
-
-
-
-
-
-
- String intercept(ActionInvocation invocation) throws Exception;
- }
Interceptor的接口定義沒(méi)有什么特別的地方,除了init和destory方法以外,intercept方法是實(shí)現(xiàn)整個(gè)攔截器機(jī)制的核心方法。而它所依賴(lài)的參數(shù)ActionInvocation則是我們之前章節(jié)中曾經(jīng)提到過(guò)的著名的
Action調(diào)度者。
我們?cè)賮?lái)看看一個(gè)典型的Interceptor的抽象實(shí)現(xiàn)類(lèi):
- public abstract class AroundInterceptor extends AbstractInterceptor {
-
-
-
-
- @Override
- public String intercept(ActionInvocation invocation) throws Exception {
- String result = null;
-
- before(invocation);
-
- result = invocation.invoke();
- after(invocation, result);
-
- return result;
- }
-
- public abstract void before(ActionInvocation invocation) throws Exception;
-
- public abstract void after(ActionInvocation invocation, String resultCode) throws Exception;
-
- }
在這個(gè)實(shí)現(xiàn)類(lèi)中,實(shí)際上已經(jīng)實(shí)現(xiàn)了最簡(jiǎn)單的攔截器的雛形。或許大家對(duì)這樣的代碼還比較陌生,這沒(méi)有關(guān)系。我在這里需要指出的是一個(gè)很重要的方法invocation.invoke()。這是ActionInvocation中的方法,而ActionInvocation是Action調(diào)度者,所以這個(gè)方法具備以下2層含義:
1. 如果攔截器堆棧中還有其他的Interceptor,那么invocation.invoke()將調(diào)用堆棧中下一個(gè)Interceptor的執(zhí)行。 2. 如果攔截器堆棧中只有Action了,那么invocation.invoke()將調(diào)用Action執(zhí)行。 所以,我們可以發(fā)現(xiàn),invocation.invoke()這個(gè)方法其實(shí)是整個(gè)攔截器框架的實(shí)現(xiàn)核心?;谶@樣的實(shí)現(xiàn)機(jī)制,我們還可以得到下面2個(gè)非常重要的推論:
1. 如果在攔截器中,我們不使用invocation.invoke()來(lái)完成堆棧中下一個(gè)元素的調(diào)用,而是直接返回一個(gè)字符串作為執(zhí)行結(jié)果,那么整個(gè)執(zhí)行將被中止。 2. 我們可以以invocation.invoke()為界,將攔截器中的代碼分成2個(gè)部分,在invocation.invoke()之前的代碼,將會(huì)在Action之前被依次執(zhí)行,而在invocation.invoke()之后的代碼,將會(huì)在Action之后被逆序執(zhí)行。 由此,我們就可以通過(guò)invocation.invoke()作為Action代碼真正的攔截點(diǎn),從而實(shí)現(xiàn)AOP。
Interceptor攔截類(lèi)型 從上面的分析,我們知道,整個(gè)攔截器的核心部分是invocation.invoke()這個(gè)函數(shù)的調(diào)用位置。事實(shí)上,我們也正式根據(jù)這句代碼的調(diào)用位置,來(lái)進(jìn)行攔截類(lèi)型的區(qū)分的。在Struts2中,Interceptor的攔截類(lèi)型,分成以下三類(lèi):
1. before before攔截,是指在攔截器中定義的代碼,它們存在于invocation.invoke()代碼執(zhí)行之前。這些代碼,將依照攔截器定義的順序,
順序執(zhí)行。
2. after after攔截,是指在攔截器中定義的代碼,它們存在于invocation.invoke()代碼執(zhí)行之后。這些代碼,將一招攔截器定義的順序,
逆序執(zhí)行。
3. PreResultListener
有的時(shí)候,before攔截和after攔截對(duì)我們來(lái)說(shuō)是不夠的,因?yàn)槲覀冃枰贏ction執(zhí)行完之后,但是還沒(méi)有回到視圖層之前,做一些事情。Struts2同樣支持這樣的攔截,這種攔截方式,是通過(guò)在攔截器中注冊(cè)一個(gè)PreResultListener的接口來(lái)實(shí)現(xiàn)的。
- public interface PreResultListener {
-
-
-
-
-
-
-
- void beforeResult(ActionInvocation invocation, String resultCode);
- }
在這里,我們看到,Struts2能夠支持如此多的攔截類(lèi)型,與其本身的數(shù)據(jù)結(jié)構(gòu)和整體設(shè)計(jì)有很大的關(guān)系。正如我在之前的文章中所提到的:
downpour 寫(xiě)道
因?yàn)锳ction是一個(gè)普通的Java類(lèi),而不是一個(gè)Servlet類(lèi),完全脫離于Web容器,所以我們就能夠更加方便地對(duì)Control層進(jìn)行合理的層次設(shè)計(jì),從而抽象出許多公共的邏輯,并將這些邏輯脫離出Action對(duì)象本身。
我們可以看到,Struts2對(duì)于整個(gè)執(zhí)行的劃分,從Interceptor到Action一直到Result,每一層都職責(zé)明確。不僅如此,Struts2還為每一個(gè)層次之前都設(shè)立了恰如其分的插入點(diǎn)。使得整個(gè)Action層的擴(kuò)展性得到了史無(wú)前例的提升。
Interceptor執(zhí)行順序 Interceptor的執(zhí)行順序或許是我們?cè)谡麄€(gè)過(guò)程中最最關(guān)心的部分。根據(jù)上面所提到的概念,我們實(shí)際上已經(jīng)能夠大致明白了Interceptor的執(zhí)行機(jī)理。我們來(lái)看看Struts2的Reference對(duì)Interceptor執(zhí)行順序的一個(gè)形象的例子。
如果我們有一個(gè)interceptor-stack的定義如下:
- <interceptor-stack name="xaStack">
- <interceptor-ref name="thisWillRunFirstInterceptor"/>
- <interceptor-ref name="thisWillRunNextInterceptor"/>
- <interceptor-ref name="followedByThisInterceptor"/>
- <interceptor-ref name="thisWillRunLastInterceptor"/>
- </interceptor-stack>
那么,整個(gè)執(zhí)行的順序大概像這樣:
在這里,我稍微改了一下Struts2的Reference中的執(zhí)行順序示例,使得整個(gè)執(zhí)行順序更加能夠被理解。我們可以看到,遞歸調(diào)用保證了各種各樣的攔截類(lèi)型的執(zhí)行能夠井井有條。
請(qǐng)注意在這里,每個(gè)攔截器中的代碼的執(zhí)行順序,在Action之前,攔截器的執(zhí)行順序與堆棧中定義的一致;而在Action和Result之后,攔截器的執(zhí)行順序與堆棧中定義的順序相反。
接下來(lái)我們就來(lái)看看源碼,看看Struts2是如何保證攔截器、Action與Result三者之間的執(zhí)行順序的。
之前我曾經(jīng)提到,ActionInvocation是Struts2中的調(diào)度器,所以事實(shí)上,這些代碼的調(diào)度執(zhí)行,是在ActionInvocation的實(shí)現(xiàn)類(lèi)中完成的,這里,我抽取了DefaultActionInvocation中的invoke()方法,它將向我們展示一切。
-
-
-
- public String invoke() throws Exception {
- String profileKey = "invoke: ";
- try {
- UtilTimerStack.push(profileKey);
-
- if (executed) {
- throw new IllegalStateException("Action has already executed");
- }
-
- if (interceptors.hasNext()) {
- final InterceptorMapping interceptor = (InterceptorMapping) interceptors.next();
- UtilTimerStack.profile("interceptor: "+interceptor.getName(),
- new UtilTimerStack.ProfilingBlock<String>() {
- public String doProfiling() throws Exception {
-
- resultCode = interceptor.getInterceptor().intercept(DefaultActionInvocation.this);
- return null;
- }
- });
- } else {
- resultCode = invokeActionOnly();
- }
-
-
-
- if (!executed) {
-
- if (preResultListeners != null) {
- for (Iterator iterator = preResultListeners.iterator();
- iterator.hasNext();) {
- PreResultListener listener = (PreResultListener) iterator.next();
-
- String _profileKey="preResultListener: ";
- try {
- UtilTimerStack.push(_profileKey);
- listener.beforeResult(this, resultCode);
- }
- finally {
- UtilTimerStack.pop(_profileKey);
- }
- }
- }
-
-
-
- if (proxy.getExecuteResult()) {
- executeResult();
- }
-
- executed = true;
- }
-
- return resultCode;
- }
- finally {
- UtilTimerStack.pop(profileKey);
- }
- }
從源碼中,我們可以看到,我們之前提到的Struts2的Action層的4個(gè)不同的層次,在這個(gè)方法中都有體現(xiàn),他們分別是:攔截器(Interceptor)、Action、PreResultListener和Result。在這個(gè)方法中,保證了這些層次的有序調(diào)用和執(zhí)行。由此我們也可以看出
Struts2在Action層次設(shè)計(jì)上的眾多考慮,每個(gè)層次都具備了高度的擴(kuò)展性和插入點(diǎn),使得程序員可以在任何喜歡的層次加入自己的實(shí)現(xiàn)機(jī)制改變Action的行為。 在這里,需要特別強(qiáng)調(diào)的,是其中攔截器部分的執(zhí)行調(diào)用:
- resultCode = interceptor.getInterceptor().intercept(DefaultActionInvocation.this);
表面上,它只是執(zhí)行了攔截器中的intercept方法,如果我們結(jié)合攔截器來(lái)看,就能看出點(diǎn)端倪來(lái):
- public String intercept(ActionInvocation invocation) throws Exception {
- String result = null;
-
- before(invocation);
-
- result = invocation.invoke();
- after(invocation, result);
-
- return result;
- }
原來(lái)在intercept()方法又對(duì)ActionInvocation的invoke()方法進(jìn)行遞歸調(diào)用,ActionInvocation循環(huán)嵌套在intercept()中,一直到語(yǔ)句result = invocation.invoke()執(zhí)行結(jié)束。這樣,Interceptor又會(huì)按照剛開(kāi)始執(zhí)行的逆向順序依次執(zhí)行結(jié)束。
一個(gè)有序鏈表,通過(guò)遞歸調(diào)用,變成了一個(gè)堆棧執(zhí)行過(guò)程,將一段有序執(zhí)行的代碼變成了2段執(zhí)行順序完全相反的代碼過(guò)程,從而巧妙地實(shí)現(xiàn)了AOP。這也就成為了Struts2的Action層的AOP基礎(chǔ)。