| 維度 | 過濾器 | 攔截器 |
|---|---|---|
| 實現機制 | 函數回調 | Java 反射 |
| 依賴容器 | 依賴 Servlet 容器 | 不依賴 Servlet 容器 |
| 作用範圍 | 幾乎所有請求 | 僅 Action 請求 |
| 訪問上下文 | 不可訪問 ActionContext/ValueStack | 可訪問 Action 上下文、值棧對象 |
| 生命周期 | 容器啟動初始化一次 | Action 生命周期中可多次調用 |
CharacterEncodingFilter)。ParamsInterceptor、ConversionErrorInterceptor。ValidationInterceptor。FileUploadInterceptor。WorkflowInterceptor 控制輸入驗證失敗後的結果導向。public class EncodingFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
throws IOException, ServletException {
req.setCharacterEncoding("UTF-8");
resp.setCharacterEncoding("UTF-8");
chain.doFilter(req, resp);
}
}
web.xml 配置:<filter>...<url-pattern>/*</url-pattern>
public class LogInterceptor extends AbstractInterceptor {
public String intercept(ActionInvocation invocation) throws Exception {
String actionName = invocation.getAction().getClass().getSimpleName();
long start = System.currentTimeMillis();
String result = invocation.invoke(); // 執行下一個攔截器或 Action
long end = System.currentTimeMillis();
log.info("Action: {} 耗時: {}ms", actionName, end - start);
return result;
}
}
struts.xml 配置:<interceptor-ref name="logInterceptor"/> 或在 <interceptor-stack> 中組合。
攔截器本質是 Struts2 實現的 基於方法級的 AOP:
invocation.invoke() 前 = @Beforeinvocation.invoke() 後 = @AfterReturninginvoke() 調用時機這使得攔截器能精細控制 Action 執行流程,甚至阻止 Action 執行(直接返回結果代碼)。