Struts2開發自定義攔截器
Interceptor接口
public interface Interceptor extends Serializable {
/**
* Called to let an interceptor clean up any resources it has allocated.
*/
void destroy();
/**
* Called after an interceptor is created, but before any requests are processed using
* {@link #intercept(com.opensymphony.xwork2.ActionInvocation) intercept} , giving
* the Interceptor a chance to initialize any needed resources.
*/
void init();
/**
* Allows the Interceptor to do some processing on the request before and/or after the rest of the processing of the
* request by the {@link ActionInvocation} or to short-circuit the processing and just return a String return code.
*
* @param invocation the action invocation
* @return the return code, either returned from {@link ActionInvocation#invoke()}, or from the interceptor itself.
* @throws Exception any system-level error, as defined in {@link com.opensymphony.xwork2.Action#execute()}.
*/
String intercept(ActionInvocation invocation) throws Exception;
}</pre>
可以看出接口中只有三個方法需要實現。
實現Interceptor接口
public class MyInterceptor implements Interceptor {
public void destroy() {
System.out.println("destroy()----");
}
public void init() {
System.out.println("init()----");
}
public String intercept(ActionInvocation invocation) throws Exception {
System.out.println("在Action執行之前");
String result = invocation.invoke();
System.out.println("在Result執行之后");
return result;
}
}
我們需要在struts.xml文件中進行配置:
<package name="helloworld" extends="struts-default">
<interceptors>
<interceptor name="MyInterceptor" class="com.lc.action.MyInterceptor" />
</interceptors>
<action name="loginAction" class="com.lc.action.LoginAction">
<param name="account">test</param>
<result>/welcome.jsp</result>
<interceptor-ref name="MyInterceptor" />
<interceptor-ref name="defaultStack" />
</action>
</package>
首先聲明一個自定義的攔截器:
<interceptors>
<interceptor name="MyInterceptor" class="com.lc.action.MyInterceptor" />
</interceptors>
然后在action中引用:
<interceptor-ref name="MyInterceptor" />
執行的結果可想而知:
在Action執行之前
account=test,password=test,submitFlag=login
在Result執行之后
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!