Struts2自定义拦截器

    自定义拦截器,一般用到的不多,如果用到,估计也就是你的设计哪里出了bug吧,但是Struts2既然有这个知识点,应该还是要学一下的。

  

 1.首先写一个类,实现Interceptor这个接口。在intercept()方法中获取action被拦截的时间。

   

package com.seven.interceptor;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
/**
 * 自定义拦截器
 * @author Administrator
 *
 */
public class MyInterceptor implements Interceptor{
	public void destroy() {}
	public void init() {}


	public String intercept(ActionInvocation invocation) throws Exception {
		long start = System.currentTimeMillis();
	        String r = invocation.invoke();
		long end=System.currentTimeMillis();
		System.out.println("action time = "+(end-start));
		return r;
	}

}
2.在struts.xml配置文件中做如下配置

 <package name="test" extends="struts-default">
     
     <interceptors>
       <interceptor name="my" class="com.seven.interceptor.MyInterceptor"></interceptor>
     </interceptors>
     
     <action name="test" class="com.seven.action.TestAction">
        <interceptor-ref name="my"></interceptor-ref>
        <interceptor-ref name="defaultStack"></interceptor-ref>
        <result>/Test.jsp</result>
     </action>
   </package>
这里defaultStack是Struts2的默认拦截器,在自定义拦截器之后,还要默认的拦截器。因为如果不加,就只有自己定义的拦截器。如果两个拦截器都不写,系统会自动调用默认的拦截器。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值