Struts2 配置第一个拦截器

MyTimerAction Action类

package action;

import com.opensymphony.xwork2.Action;

public class MyTimerAction implements Action {
	public String execute() throws Exception {
		return SUCCESS;
	}
}

 

MyTimerInterceptor 拦截器类

package interceptor;

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

public class MyTimerInterceptor extends AbstractInterceptor {

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		//1、执行 Action 之前的工作:获取开始执行时间
		long startTime = System.currentTimeMillis();
		System.out.println("执行 Action 之前的工作,开始时间"+startTime);
		//2、执行后续拦截器或 Action
		String result = invocation.invoke();
		//3、执行 Action 之后的工作:计算并输出执行时间
		long endTime = System.currentTimeMillis();
		long execTime = endTime - startTime;
		System.out.println("执行 Action 后的,结束时间"+endTime);
		System.out.println("总共用时"+execTime);
		//返回结果字符串
		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>
	<!-- 开发者模式,输出更多调试信息 -->
	<constant name="struts.devMode" value="true"></constant>
	<package name="default" namespace="/" extends="struts-default">
		<!-- 所有的定义拦截器 -->
		<interceptors>
			<!-- 定义拦截器 -->
			<interceptor name="myTimer" class="interceptor.MyTimerInterceptor"></interceptor>
		</interceptors>
		<action name="action" class="action.MyTimerAction">
			<result name="success">/index.jsp</result>
			<!-- 为 Action 指定拦截器引用 -->
			<interceptor-ref name="myTimer"></interceptor-ref>
			<interceptor-ref name="defaultStack"></interceptor-ref>
		</action>
	</package>
</struts>

 

效果图:
Struts2 配置第一个拦截器

 

Struts2 配置第一个拦截器