前兩天實踐了關于攔截器的具體實現,說實話關于底層實現還沒有看明白,看jdk的源碼中的
public static Class<?> getProxyClass(ClassLoader loader,Class<?>... interfaces)
方法,好長啊
迂回一下,今兒看struts2的具體攔截器Interceptor怎么配置
配置可比自己寫實現攔截器容易多了
1、首先寫一個攔截器類,攔截器類有兩只寫法(目前俺知道的)
一種是顯示com.opensymphony.xwork2.interceptor.Interceptor接口,com.opensymphony.xwork2.interceptor.Interceptor接口有三個方法destroy()、init()和String intercept(ActionInvocation actionInvocation),跟過濾器差不多
這里指出的是init初始化方法將在容器啟動是調用這個方法。
package com.test.interceptor;
/**
* Created by IntelliJ IDEA.
* User: Administrator
* Date: 2009-1-15
* Time: 16:34:17
* To change this template use File | Settings | File Templates.
*/
import com.opensymphony.xwork2.interceptor.Interceptor;
import com.opensymphony.xwork2.ActionInvocation;
public class MyInterceptor implements Interceptor{
public void destroy() {
}
public void init() {
}
public String intercept(ActionInvocation actionInvocation) throws Exception {
System.out.println("test intercept begin");
String result = actionInvocation.invoke();
System.out.println("test intercept finish");
return result;
}
}
另一種就是繼承com.opensymphony.xwork2.interceptor.AbstractInterceptor,這是個抽象類,并實現了com.opensymphony.xwork2.interceptor.Interceptor接口,分別實現了init和destroy方法,但什么都沒做,繼承AbstractInterceptor后,實現intercept方法就行了,
這里指出的是在intercept方法中執行actionInvocation.invoke();執行所攔截的action中的方法;
2、攔截器寫完了剩下就是配置了,這里要用到struts.xml的組織結構<struts>中有<package>包的的概念,包與包之間可以繼承extends,就像子類繼承父類一樣,子類將擁有父類的屬性和配置,我們一般都繼承extends="struts-default",而struts-default定義在struts2-core.jar 中的struts-default.xml中,struts-default包中定義了很多struts2提供的攔截器和攔截器棧(攔截器棧可以包含多個攔截器或攔截器棧),struts2的好多功能都是實現在這些攔截器中,其中有個<default-interceptor-ref name="defaultStack"/>標簽定義了默認的攔截器,如果<action>配置中沒有攔截器配置,那就調用默認攔截器,如果有攔截器配置,要么同時加上默認攔截器,要么在自己的package中加入設置默認攔截器的標簽。
<package name="capinfo" extends="struts-default">
<interceptors>
<interceptor name="myInterceptor" class="com.test.interceptor.MyInterceptor">
</interceptor>
</interceptors>
<action name="HelloWorld"
class="com.capinfo.struts2.action.HelloWordAction">
<result>/HelloWorld.jsp</result>
<interceptor-ref name="myInterceptor"></interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
</action>
<!-- Add your actions here -->
</package>