Stutus2拦截器(2)

140 阅读1分钟

Stutus2拦截器(2)–自定义拦截器

第一步:实现AbstratIntercepter, 重写intercept()
第二步: 在strtus.xml中注册Interceptor

第一步:实现AbstratIntercepter, 重写intercept()

public class TimerInterceptor extends AbstractInterceptor {

    @Override
    public String intercept(ActionInvocation invocation) throws Exception {
        // 1.执行Action之前
        long start = System.currentTimeMillis();
        // 2.执行下一个拦截器,如果已经是最后一个拦截器,则执行目标Action
        String result = invocation.invoke();
        // 3.执行Action之后
        long end = System.currentTimeMillis();
        System.out.println("执行Action花费的时间:" + (end - start) + "ms");

        return result;
    }

}

第二步: 在strtus.xml中注册Interceptor

<?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.enable.DynamicMethodInvocation" value="false" />
    <constant name="struts.devMode" value="true" />

    <package name="default" namespace="/" extends="struts-default">
        <!-- 注册拦截器 -->
        <interceptors>
            <interceptor name="mytimer"
                class="com.imooc.interceptor.TimerInterceptor" />
        </interceptors>

        <action name="timer" class="com.imooc.action.TimerAction">
            <result>/success.jsp</result>
            <!-- 为Action显示引用拦截器后,默认的拦截器defaultStack不再生效,需要手工引用 -->
            <interceptor-ref name="defaultStackz"></interceptor-ref>
            <!-- 引用拦截器 -->
            <interceptor-ref name="mytimer" />
        </action>
    </package>
</struts>