十一、利用拦截器统计action执行时间

1.新建login.jsp

<body>
    <a href="HelloAction.action">点击统计action执行时间</a>
</body>

2.新建Action

package com.myz.action;

import com.opensymphony.xwork2.ActionSupport;

public class HelloAction extends ActionSupport {
    
    @Override
    public String execute() throws Exception {
        // TODO Auto-generated method stub
        return SUCCESS;
    }
}

3.新建拦截器

package com.myz.action;


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

public class TimerInterceptor extends AbstractInterceptor {

    @Override
    public String intercept(ActionInvocation invocation) throws Exception {
        // TODO Auto-generated method stub
        //开始时候的毫秒数
        long start = System.currentTimeMillis();
        //2.执行下一个拦截器,如果已是最后一个拦截器,则执行目标action
        String invoke = invocation.invoke();
        //3.执行完的毫秒数
        long end = System.currentTimeMillis();
        System.out.println("action执行时间:"+(end-start)+"ms");
        return invoke;
    }

}

4.配置拦截器

<?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>
    <package name="default" namespace="/" extends="struts-default">
    
        <!-- 注册拦截器 -->
        <interceptors>
            <interceptor name="mytimer" class="com.myz.action.TimerInterceptor"></interceptor>
        </interceptors>
        
        <action name="HelloAction" class="com.myz.action.HelloAction">
            
            <result>/loginok.jsp</result>
            
            <!-- 引用拦截器 -->
            <interceptor-ref name="mytimer"></interceptor-ref>
        </action>
        
    </package>
    
</struts>    

5.发布项目,http://localhost:8080/InterceptorTest/login.jsp,点击统计,后台输出action执行时间

原文地址:https://www.cnblogs.com/myz666/p/8458433.html