接觸 Struts2 一段時間後會發現,它的核心正是透過攔截器包住 Action,藉此完成 View 層的控制跳轉。Struts2 把 Servlet API 與業務處理分離,讓開發者在請求進來時能以攔截機制做前置與後置處理。以下用幾個純 Java 類別把這個機制模擬出來。
核心是責任鏈:每個攔截器在呼叫 invoke() 前後插入自己的邏輯,由一個「呼叫上下文」負責依序推進,鏈走完才交給真正的 Action。
package com.simulink;
import java.util.ArrayList;
import java.util.List;
public class AntionInvocation {
Action a = new Action();
int index = -1;
List<Interceptor> interceptors = new ArrayList<Interceptor>();
public AntionInvocation() {
interceptors.add(new FirstInterceptor());
interceptors.add(new SecondInterceptor());
}
public void invoke() {
index++;
if (index >= this.interceptors.size()) {
a.execute(); // 鏈走完,交給 Action
} else {
this.interceptors.get(index).intercept(this);
}
}
}
package com.simulink;
public class FirstInterceptor implements Interceptor {
@Override
public void intercept(AntionInvocation invocation) {
System.out.println(-1);
invocation.invoke(); // 遞迴推進到下一個攔截器
System.out.println(1);
}
}
package com.simulink;
public class SecondInterceptor implements Interceptor {
@Override
public void intercept(AntionInvocation invocation) {
System.out.println(-2);
invocation.invoke();
System.out.println(2);
}
}
package com.simulink;
public class Action {
public void execute() {
System.out.println("execute!");
}
}
package com.simulink;
public class Main {
public static void main(String[] args) {
new AntionInvocation().invoke();
}
}
-1 -2 execute! 2 1
這個「先進後出」的順序正是攔截器的精髓:invoke() 之前的程式碼構成前置處理,之後的程式碼構成後置處理,因此外層攔截器的後置邏輯最後才執行。Struts2 的拦截器堆疊、result 選擇、preResult 與 postResult 行為,本質上都是這套機制的延伸。
後記:用過 WebWork 的人會發現 Struts2 與它極為相似——實際上 Struts2 就是 Struts1 與 WebWork 的結合體,主要技術多來自 WebWork。以上內容為個人學習整理,若有理解不周之處還請指正。