概念:什么是攔截器
攔截器實現了面向切面的組件,它會影響多個業務對象的公共行為封裝到一個個可重用的模塊,減少了系統的重復代碼,實現高度內聚,確保業務對象的整潔!
為什么使用攔截器
攔截器消除了動作組件中的橫切任務,為系統處理每一個請求完成的管理任務!
攔截器的工作原理
當框架接受到一個請求的時候,它首先必須決定這uri映射到哪一個動作組件,這動作組件的實例就會被加入到一個新創建的Actionlnvocation實例中,然后框架將會驗證哪一些攔截器將會被激活觸發(xml文件中的配置),以及按照聲明的順序觸發。然后將這些攔截器的引用添加到Actionlnvocation中,Actionlnvocation創建並填充了需要的所有對象、信息完畢后,Actionlnvocation則公開了一個invoake()方法,框架然后則調用這個方法並開始繼續執行后面的動作!
1、攔截器 Interceptor的實現方式
實現 Interceptor 接口,實現 intercept 方法
繼承 AbstractInterceptor類( 推薦 ),重寫 intercept 方法
2、編寫攔截器
從session中獲取。。。。。
3、在struts.xml文件中配置攔截器
一、單個攔截器:name為攔截器的名稱,class是編寫的攔截器
<!-- 定義的攔截器 -->
<interceptors>
<interceptor name="test" class="com.Interceptor.MyInterceptor"></interceptor>
</interceptors>
二、攔截器棧
<interceptors>
<interceptor name="test" class="com.interceptor.MyInterceptor"></interceptor>
<interceptor-stack name="mystac">
<interceptor-ref name="test1"></interceptor-ref>
<interceptor-ref name="test2"></interceptor-ref>
</interceptor-stack>
</interceptors>
4、攔截器在action中的引用
index.jsp:登錄成功之后的頁面!
<global-results>:全局結果集,非法登錄則調回原頁面!
登錄測試: