1、Struts2 攔截器
- 攔截器(Interceptor)是 Struts 2 的核心組成部分。
- Struts2 很多功能都是構(gòu)建在攔截器基礎(chǔ)之上的,例如文件的上傳和下載、國際化、數(shù)據(jù)類型轉(zhuǎn)換和數(shù)據(jù)校驗等等。
- Struts2 攔截器在訪問某個 Action 方法之前或之后實施攔截
- Struts2 攔截器是可插拔的, 攔截器是 AOP(面向切面編程) 的一種實現(xiàn).
攔截器棧(Interceptor Stack): 將攔截器按一定的順序聯(lián)結(jié)成一條鏈. 在訪問被攔截的方法時, Struts2 攔截器鏈中的攔截器就會按其之前定義的順序被依次調(diào)用- 從攔截器進去,再從攔截器出來
2、 Struts2自帶的攔截器

3、Interceptor 接口
- 每個攔截器都是實現(xiàn)了 com.opensymphony.xwork2.interceptor.Interceptor 接口的 Java 類:
public interface Interceptor extends Serializable {
void destroy();
void init();
String intercept(ActionInvocation invocation) throws Exception;
}
-
init: 該方法將在攔截器被創(chuàng)建后立即被調(diào)用, 它在攔截器的生命周期內(nèi)只被調(diào)用一次. 可以在該方法中對相關(guān)資源進行必要的初始化 -
interecept: 每攔截一個請求, 該方法就會被調(diào)用一次. -
destroy: 該方法將在攔截器被銷毀之前被調(diào)用, 它在攔截器的生命周期內(nèi)也只被調(diào)用一次. -
Struts會依次調(diào)用為某個 Action 而注冊的每一個攔截器的 interecept 方法. - 每次調(diào)用 interecept 方法時, Struts 會傳遞一個
ActionInvocation 接口的實例. -
ActionInvocation: 代表一個給定 Action 的執(zhí)行狀態(tài), 攔截器可以從該類的對象里獲得與該 Action 相關(guān)聯(lián)的 Action 對象和 Result 對象. 在完成攔截器自己的任務(wù)之后, 攔截器將調(diào)用 ActionInvocation 對象的 invoke 方法前進到 Action 處理流程的下一個環(huán)節(jié). -
AbstractInterceptor類實現(xiàn)了 Interceptor 接口. 并為 init, destroy 提供了一個空白的實現(xiàn)
4、自定義攔截器
-
定義自定義攔截器的步驟
- 自定義攔截器
- 在 struts.xml 文件中配置自定義的攔截器
示例代碼:
自定義攔截器
public class MyInterceptor extends AbstractInterceptor{
public String intercept(ActionInvocation invocation) throws Exception {
System.out.println("before invocation.invoke...");
String result = invocation.invoke();
System.out.println("after invocation.invoke...");
return result;
//return "success"; 直接返回一個值,將不會調(diào)用后面的攔截器
}
}
- 在struts.xml配置文件中注冊攔截器-在package標簽中注冊攔截器
<interceptors>
<!-- 配置攔截器 -->
<interceptor name="myInterceptor" class="org.pan.struts.interceptor.MyInterceptor"/>
<interceptor-stack name="myIntercepterStack">
<interceptor-ref name="paramsPrepareParamsStack"/>
</interceptor-stack>
</interceptors>
- 使用攔截器: 在action中使用攔截器
- 注意:如果在action中引用了自定義攔截器,那么還需要在引入默認的攔截器棧,
- 如果不引用則整個Action只會經(jīng)過自定義攔截器,而不會在調(diào)用其他的攔截器,
- 通過interceptor-ref來決定攔截器的執(zhí)行位置,越靠前則越先執(zhí)行
<action name="user_*" class="org.pan.struts.action.TestValidationAction" method="{1}">
<!--使用攔截器 -->
<interceptor-ref name="myInterceptor"/>
<!-- 還需要引用攔截器器棧 -->
<interceptor-ref name="myIntercepterStack"/>
<result name="success">/WEB-INF/views/success.jsp</result>
<result name="{1}">/WEB-INF/views/{1}.jsp</result>
<result name="input">/WEB-INF/views/input.jsp</result>
</action>

