今天學了struts2的攔截器,對攔截器的實現原理有了一定的瞭解。
下面是根據老師帶領,完成的一個自定義攔截器 。
第一步:
寫一個自己的攔截器類。MyTimerInterceptor.java ,實現Interceptor接口,並實現這個接口中的方法。有三種方法,如下:
(1) init()方法用來初始化攔截器
(2) destroy()方法爲攔截器提供清理,也就是銷燬的時候執行
(3) intercept()方法爲攔截器處理業務規則,這個方法每次請求都執行一次
代碼如下:
import javax.interceptor.InvocationContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
public class MyTimerInterceptor implements Interceptor{
//銷燬的方法
public void destroy() {
System.out.println("銷燬的時候執行一次");
}
public void init() {
System.out.println("初始化的時候執行一次");
}
public String intercept(ActionInvocation invocation) throws Exception {
//當前處理的action::::::cn.csdn.hr.struts.inter.action.MyInterceptorAction@195edfe
Object obj = invocation.getAction();
System.out.println(obj.toString());
long mil = System.currentTimeMillis();
System.out.println("目標方法執行之前:........"+System.currentTimeMillis());
String result = invocation.invoke();//執目標方法
System.out.println(result+"目標方法執行之後.......共花費時間爲:"+(System.currentTimeMillis()-mil));
System.out.println("每次請求的時候都執行一次");
return result;
}
}
第二步:
將struts.xml進行配置。 配置一個自定義的攔截器。
代碼如下:以及一些配置需要的解析如下:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<package name="empl" extends="struts-default" namespace="/csdn">
<!-- 攔截器的聲明 -->
<interceptors>
<!-- 聲明自定義攔截器 -->
<interceptor name="myTimer"
class="cn.csdn.hr.struts.inter.MyTimerInterceptor" />
<!-- 聲明攔截器棧 -->
<interceptor-stack name="myStack">
<interceptor-ref name="myTimer" />
<interceptor-ref name="defaultStack" />
</interceptor-stack>
</interceptors>
<!-- 配置缺省的 攔截器棧 -->
<default-interceptor-ref name="myStack" />
<action name="helloInter"
class="cn.csdn.hr.struts.inter.action.MyInterceptorAction" method="execute">
<interceptor-ref name="myTimer"/>
<result>../sc.jsp</result>
</action>
<action name="hiInter"
class="cn.csdn.hr.struts.inter.action.MyInterceptorAction" method="say">
<result>../sc.jsp</result>
</action>
</package>
</struts>
以上這個程序執行的結果如下所示:
cn.csdn.hr.struts.inter.action.MyInterceptorAction@f631d8
目標方法執行之前:........1331118970703
success目標方法執行之後.......共花費時間爲:187
每次請求的時候都執行一次