struts2拦截器

struts2的拦截器:

拦截器,在AOP(Aspect-Oriented Programming)中用于在某个方法或字段被访问之前,进行拦截然后在之前或之后加入某些操作。拦截是AOP的一种实现策略。

    在 Webwork的中文文档的解释为——拦截器是动态拦截Action调用的对象。它提供了一种机制可以使开发者可以定义在一个action执行的前后执行的代码,也可以在一个action执行前阻止其执行。同时也是提供了一种可以提取action中可重用的部分的方式。

    谈到拦截器,还有一个词大家应该知道——拦截器链(Interceptor Chain,在Struts 2中称为拦截器栈Interceptor Stack)。拦截器链就是将拦截器按一定的顺序联结成一条链。在访问被拦截的方法或字段时,拦截器链中的拦截器就会按其之前定义的顺序被调用。

struts2中那些已经定义好的拦截器就不说了。

下面是我做的一个拦截器timer的例子,很简单。

package struts2;

import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("serial")
public class TimerInterceptorAction extends ActionSupport{
 
 public String execute(){
    try{
            // 模拟耗时的操作
           Thread.sleep(500);
       } catch (Exception e)  {
           e.printStackTrace();
       }
        return SUCCESS;

 }

 
}

struts.xml中的配置:

<! DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
        "http://struts.apache.org/dtds/struts-2.0.dtd"
>
< struts >
   
< include file ="struts-default.xml" />    
   
< package name ="struts2" extends ="struts-default" >
       
< action name ="Timer" class ="struts2.TimerInterceptorAction" >
           
< interceptor-ref name ="timer" />
           
< result > /Timer.jsp </ result >
       
</ action >
   
</ package >
</ struts >

 

 

 

在控制台输出为:

2010-11-28 20:30:09 com.opensymphony.xwork2.interceptor.TimerInterceptor doLog
信息: Executed action [//Timer!execute] took 503 ms.

 

就这样可以了。

 

 

 

你可能感兴趣的:(apache,AOP,jsp,struts,Webwork)