前兩天實(shí)踐了關(guān)于攔截器的具體實(shí)現(xiàn),說實(shí)話關(guān)于底層實(shí)現(xiàn)還沒有看明白,看jdk的源碼中的
public static Class<?> getProxyClass(ClassLoader loader,Class<?>... interfaces)
方法,好長啊
迂回一下,今兒看struts2的具體攔截器Interceptor怎么配置
配置可比自己寫實(shí)現(xiàn)攔截器容易多了
1、首先寫一個(gè)攔截器類,攔截器類有兩只寫法(目前俺知道的)
一種是顯示com.opensymphony.xwork2.interceptor.Interceptor接口,com.opensymphony.xwork2.interceptor.Interceptor接口有三個(gè)方法destroy()、init()和String intercept(ActionInvocation actionInvocation),跟過濾器差不多
這里指出的是init初始化方法將在容器啟動(dòng)是調(diào)用這個(gè)方法。
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,這是個(gè)抽象類,并實(shí)現(xiàn)了com.opensymphony.xwork2.interceptor.Interceptor接口,分別實(shí)現(xiàn)了init和destroy方法,但什么都沒做,繼承AbstractInterceptor后,實(shí)現(xiàn)intercept方法就行了,
這里指出的是在intercept方法中執(zhí)行actionInvocation.invoke();執(zhí)行所攔截的action中的方法;
2、攔截器寫完了剩下就是配置了,這里要用到struts.xml的組織結(jié)構(gòu)<struts>中有<package>包的的概念,包與包之間可以繼承extends,就像子類繼承父類一樣,子類將擁有父類的屬性和配置,我們一般都繼承extends="struts-default",而struts-default定義在struts2-core.jar 中的struts-default.xml中,struts-default包中定義了很多struts2提供的攔截器和攔截器棧(攔截器棧可以包含多個(gè)攔截器或攔截器棧),struts2的好多功能都是實(shí)現(xiàn)在這些攔截器中,其中有個(gè)<default-interceptor-ref name="defaultStack"/>標(biāo)簽定義了默認(rèn)的攔截器,如果<action>配置中沒有攔截器配置,那就調(diào)用默認(rèn)攔截器,如果有攔截器配置,要么同時(shí)加上默認(rèn)攔截器,要么在自己的package中加入設(shè)置默認(rèn)攔截器的標(biāo)簽。
<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>