Struts2的攔截器
1、Struts2的攔截器只能攔截Action,攔截器是AOP的一種思路,可以使我們的系統架構
更松散(耦合度低),可以插拔,容易互換,代碼不改變的情況下很容易滿足客戶需求
其實體現了OCP
2、如何實現攔截器?(整個攔截器體現了責任鏈模式,Filter也體現了責任鏈模式)
* 繼承AbstractInterceptor(體現了缺省適配器模式,建議使用該模式)
* 實現Interceptor
3、如果自定了攔截器,缺省攔截器會失效,必須顯示引用Struts2默認的攔截器
4、攔截器棧,多個攔截器的和
5、定義缺省攔截器<default-interceptor-ref>,所有的Action都會使用
6、攔截器的執行原理,在ActionInvocation中有一個成員變量Iterator,這個Iterator中保存了所有的
攔截器,每次都會取得Iterator進行next,如果找到了攔截器就會執行,否則就執行Action,都執行完了
攔截器出棧(其實出棧就是攔截器的intercept方法彈出棧)
自定義攔截器myLogInterceptor.java
package com.djoker.struts2; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.interceptor.AbstractInterceptor; public class myLogInterceptor extends AbstractInterceptor { @Override public String intercept(ActionInvocation invocation) throws Exception { System.out.println("記錄日志開始"); String recode = invocation.invoke(); System.out.println("記錄日志結束"); return recode; } }
struts.xml配置攔截器
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN" "http://struts.apache.org/dtds/struts-2.1.7.dtd"> <struts> <package name="user" extends="struts-default" namespace="/user"> <interceptors> <!-- 聲明過濾器 --> <interceptor name="mylog" class="com.djoker.struts2.myLogInterceptor"></interceptor> <!-- 使用站方式聲明過濾器 --> <interceptor-stack name="myStack"> <interceptor-ref name="defaultStack"></interceptor-ref> <interceptor-ref name="mylog"></interceptor-ref> </interceptor-stack> </interceptors> <!-- 默認攔截器,如果沒有指定則使用該攔截器 --> <default-interceptor-ref name="myStack"></default-interceptor-ref> <global-exception-mappings> <exception-mapping result="error" exception="com.djoker.struts2.UserNotFoundException"></exception-mapping> </global-exception-mappings> <action name="*User" class="com.djoker.struts2.UserAction" method="{1}User"> <!-- 普通配置,但是每個Action都需要配置 <interceptor-ref name="defaultStack"></interceptor-ref> <interceptor-ref name="mylog"></interceptor-ref> --> <!-- <interceptor-ref name="mylog"></interceptor-ref> --> <exception-mapping result="error" exception="com.djoker.struts2.UserNotFoundException"></exception-mapping> <result>/success.jsp</result> <result name="error">/error.jsp</result> </action> </package> </struts>