struts2基礎——自訂攔截器,struts2基礎攔截
一、自訂攔截器
預設的攔截器能實現的功能是有限的,Struts2 支援自訂攔截器。
二、攔截器類
1.實現 Interceptor 介面
2.繼承 AbstractInterceptor 抽象類別,需要實現 public String intercept(ActionInvocation actionInvocation) 方法,其中通過 actionInvocation.invoke() 繼續調用後續攔截器 和 Action 方法。
Struts2 會自動跳轉到自訂攔截器的 interceptor 方法傳回值對應的 result,如果直接返回一個 String,那麼會將控制器交給目標 action 對應的 result。
3.註冊自訂攔截器與使用
(1)Action 級
<package name="default" namespace="/" extends="struts-default"> <interceptor name="myInterceptor" class="com.nucsoft.struts.interceptor.MyInterceptor"/> <action name="interceptor" class="com.nucsoft.struts.token.InterceptorAction"> <interceptor-ref name="myInterceptor"/> <interceptor-ref name="defaultStack"/> <result>/success.jsp</result> <result name="input">/error.jsp</result> </action>
</package>
(2)package 級
<package name="default" namespace="/" extends="struts-default"> <interceptors> <interceptor name="myInterceptor" class="com.nucsoft.struts.interceptor.MyInterceptor"/> <interceptor-stack name="myInterceptorStack"> <interceptor-ref name="myInterceptor"/> <interceptor-ref name="defaultStack"/> </interceptor-stack> </interceptors> <default-interceptor-ref name="myInterceptorStack"/> <action name="myInterceptor" class="com.nucsoft.struts.token.InterceptorAction" method="myInterceptor"> <result>/success.jsp</result> <result name="input">/error.jsp</result> </action></package>