攔截器是 Struts2 核心擴展點,實現橫切關注點(參數封裝、類型轉換、驗證、文件上傳、國際化等)的即插即用組合。
攔截器在 Action 的 execute() 執行前後、Result 渲染前後插入通用邏輯,類似 Servlet Filter 但僅攔截 Action 請求,不攔截靜態資源(JSP、CSS、JS)。
ActionInvocation.invoke()。intercept(invocation)。
3. 攔截器內部調用 invocation.invoke() 將控制權傳給下一個攔截器(遞歸調用)。
4. 最後一個攔截器調用 Action.execute()。
5. 返回時按相反順序回退執行攔截器後置邏輯。
6. 任一攔截器直接返回結果字符串可終止後續執行(短路)。
本質:責任鏈模式 + 命令模式的遞歸實現。
<interceptor-stack name="defaultStack">
<interceptor-ref name="exception"/> <!-- 異常映射 -->
<interceptor-ref name="alias"/> <!-- 參數別名 -->
<interceptor-ref name="servletConfig"/> <!-- Servlet API 注入 -->
<interceptor-ref name="i18n"/> <!-- 國際化 -->
<interceptor-ref name="prepare"/> <!-- Preparable 接口回調 -->
<interceptor-ref name="chain"/> <!-- Action 鏈 -->
<interceptor-ref name="modelDriven"/> <!-- ModelDriven 接口 -->
<interceptor-ref name="fileUpload"/> <!-- 文件上傳 -->
<interceptor-ref name="params"/> <!-- 參數綁定 -->
<interceptor-ref name="validation"> <!-- 驗證 -->
<param name="excludeMethods">input,back,cancel,browse</param>
</interceptor-ref>
<interceptor-ref name="workflow"> <!-- 驗證失敗短路 -->
<param name="excludeMethods">input,back,cancel,browse</param>
</interceptor-ref>
<!-- debugging, deprecation 等 -->
</interceptor-stack>
package cn.wz.logindemo;
import com.opensymphony.xwork2.*;
import com.opensymphony.xwork2.interceptor.Interceptor;
import java.util.Map;
public class MyInterceptor implements Interceptor {
public String intercept(ActionInvocation inv) throws Exception {
ActionContext ctx = inv.getInvocationContext();
Map<String, Object> session = ctx.getSession();
if (session.containsKey("userName")) {
return inv.invoke(); // 已登錄,繼續鏈
}
return "input"; // 未登錄,短路返回 input 結果
}
public void init() {}
public void destroy() {}
}
<interceptors>
<interceptor name="loginCheck" class="cn.wz.logindemo.MyInterceptor"/>
<interceptor-stack name="myStack">
<interceptor-ref name="defaultStack"/>
<interceptor-ref name="loginCheck"/>
</interceptor-stack>
</interceptors>
<default-interceptor-ref name="myStack"/>
<action name="secureAction" class="...">
<result name="input">/login.jsp</result> <!-- 未登錄跳轉登錄頁 -->
<result name="success">/welcome.jsp</result>
</action>

攔截器是 Struts2 實現 AOP 的關鍵機制。掌握默認棧組成、執行流程與自定義開發,能精準控制請求處理管道,實現認證授權、日誌審計、事務管理等橫切需求。