java技術(shù)棧中典型的SSH里面,Struts為Web開發(fā)提供了良好的MVC支持,在基于Servlet API標(biāo)準(zhǔn)的MVC實(shí)現(xiàn)中,有的基于javax.servlet.Servlet實(shí)現(xiàn),有的基于javax.servlet.Filter實(shí) 現(xiàn),Struts是基于Filter實(shí)現(xiàn)的。
如果要實(shí)現(xiàn)“攔截”, “過(guò)濾”的語(yǔ)義,自然可以用標(biāo)準(zhǔn)的javax.servlet.Filter實(shí)現(xiàn),但是如果項(xiàng)目中已經(jīng)使用了了Struts,那么可以選著用更加“Struts”的方式Interceptor實(shí)現(xiàn)。
攔截器(Interceptor)在Struts中是一個(gè)很基礎(chǔ)的組件,整個(gè)Struts框架的許多功能都是由攔截器實(shí)現(xiàn)的,比如數(shù)據(jù)驗(yàn)證,方法調(diào)用過(guò)濾,國(guó)際化等,每一個(gè)功能都有一個(gè)對(duì)應(yīng)的攔截器在應(yīng)用啟動(dòng)時(shí)被配置到Action的調(diào)用鏈中。
攔截器即一種可以在Action執(zhí)行之前和(或)之后執(zhí)行額外動(dòng)作的組件,每一個(gè)Action在執(zhí)行前后可以配置任意數(shù)量的攔截器。
通過(guò)在中聲明攔截器,然后通過(guò)引用
<package name="default" extends="struts-default"> <interceptors> <interceptor name="timer" class=".."/> <interceptor name="logger" class=".."/> </interceptors> <action name="login" class="tutorial.Login"> <interceptor-ref name="timer"/> <interceptor-ref name="logger"/> <result name="input">login.jsp</result> <result name="success" type="redirectAction">/secure/home</result> </action></package>攔截器可以分組成stack,這樣對(duì)Interceptor Stack的引用即等同于對(duì)其中所有攔截器的引用,其中的攔截器按在stack中聲明的順序被執(zhí)行.
<package name="default" extends="struts-default"> <interceptors> <interceptor name="timer" class=".."/> <interceptor name="logger" class=".."/> <interceptor-stack name="myStack"> <interceptor-ref name="timer"/> <interceptor-ref name="logger"/> </interceptor-stack> </interceptors> <action name="login" class="tutuorial.Login"> <interceptor-ref name="myStack"/> <result name="input">login.jsp</result> <result name="success" type="redirectAction">/secure/home</result> </action></package>通過(guò)實(shí)現(xiàn)com.opensymphony.xwork2.interceptor.Interceptor可以創(chuàng)建自定義的攔截器
public interface Interceptor extends Serializable { void destroy(); void init(); String intercept(ActionInvocation invocation) throws Exception;}init(),destroy()分別在攔截器被創(chuàng)建后,intercept()被調(diào)用前以及攔截器被銷毀前創(chuàng)建。intercept()在每一次Action執(zhí)行之前被調(diào)用,ActionInvocation.invoke()將會(huì)執(zhí)行攔截器鏈中的下一個(gè)攔截器或者Action本身。
AbstractInterceptor提供了Interceptor接口init(), destroy()的一個(gè)空實(shí)現(xiàn),可用于創(chuàng)建不需要實(shí)現(xiàn)這些方法的攔截器。
Action在每次被調(diào)用時(shí)都會(huì)有一個(gè)新的對(duì)象生成,不用實(shí)現(xiàn)thread-safe,與之相反,攔截器(Interceptor)的實(shí)現(xiàn)需要保證thread-safe,因?yàn)橐粋€(gè)攔截器被多次Action調(diào)用共享。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注