配置和使用拦截器

配置和使用拦截器

struts-default.xml中已经配置了以上的拦截器。如果您想要使用上述拦截器,只需要在应用程序struts.xml文件中通过“<include file="struts-default.xml" />”struts-default.xml文件包含进来,并继承其中的struts-default包(package),最后在定义Action时,使用“<interceptor-ref name="xx" />”引用拦截器或拦截器interceptor stack)。一旦您继承了struts-default包(package),所有Action都会调用拦截器 ——defaultStack。当然,在Action配置中加入“<interceptor-ref name="xx" />”可以覆盖defaultStack

下面是关于拦截器timer使用的例子。首先,新建Actiontuotrial/TimerInterceptorAction.java,内容如下:

package tutorial;

import com.opensymphony.xwork2.ActionSupport;

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

return SUCCESS;
}

}

配置Action,名为Timer,配置文件如下:

<! 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 ="InterceptorDemo" extends ="struts-default" >
< action name ="Timer" class ="tutorial.TimerInterceptorAction" >
< interceptor-ref name ="timer" />
< result > /Timer.jsp </ result >
</ action >
</ package >
</ struts >

原文地址:https://www.cnblogs.com/chenzhao/p/2109559.html