欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Struts 2.0拦截器

程序员文章站 2022-07-12 18:21:42
...
在Struts 2.0 中的拦截器,要实现com.opensymphony.xwork2.interceptor.Interceptor接口,在struts.xml中配置。可以用拦截器来完成调用Action业务逻辑之前的预处理或是之后的善后处理。还可以通过配置多个拦截器来满足action需求。

Interceptor stack是由多个拦截器组成的拦截器组,在拦截器组中可以对每一个拦截器映射。所有进行配置拦截器时,不必对每一个拦截器进行配置,而只需对interceptor stack进行配置即可。在struts 2中默认配置了一个全局interceptor stack,包括Exception Interceptor、Validation Interceptor等。

在这个实例当中,我将配置一个时间拦截器,用来统计每个action的请求时间。

package interceptor;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

public class ActionTimer implements Interceptor{
public String intercept(ActionInvocation next) throws Exception {
long t1 = System.currentTimeMillis();
String s= next.invoke();
long t2 = System.currentTimeMillis();
System.out.println("Action "+next.getAction().getClass().getName()+" took "+(t2-t1)+" millisecs");
return s;
}

public void init() {
}
public void destroy() {
}
}


struts.xml
 
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="interceptor" extends="struts-default">
<interceptors>
<interceptor name="actiontimer"
class="interceptor.ActionTimer" />

<interceptor-stack name="demostack">
<interceptor-ref name="defaultStack" />
<interceptor-ref name="actiontimer" />
</interceptor-stack>
</interceptors>
<default-interceptor-ref name="demostack" />
<action name="InterceptorDemo"
class="interceptor.action.InterceptorDemo">
<result>http://www.bt285.cn /interceptor/interceptordemo.jsp</result>
</action>
</package>

</struts>