如何使用拦截器获取控制器执行时间并将其注入bean以json格式显示

时间:2014-04-23 08:25:08

标签: spring spring-mvc

我正在使用Spring,我对拦截器很新。现在我在我的控制器中使用System.currentTimeMillis()捕获每个请求执行时间,在bean中设置执行时间并返回该bean以JSON格式显示。

现在我想使用拦截器来帮助我的应用程序实现这样的功能。我测试了一些示例,但在从控制器返回bean值后调用了postHandle(..)afterCompletion(),我无法设置executionTime

以下是我的示例bean属性:

private String status;
private Long executionTime;
private String message;
private String id;  

请你善意地建议我这样做的正确方向。谢谢!

2 个答案:

答案 0 :(得分:1)

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

public class ExecuteTimeInterceptor extends HandlerInterceptorAdapter{

private static final Logger logger =  Logger.getLogger(ExecuteTimeInterceptor.class);

//before the actual handler will be executed
 @Override
public boolean preHandle(HttpServletRequest request, 
    HttpServletResponse response, Object handler)
    throws Exception {

    long startTime = System.currentTimeMillis();

    System.out.println("startTime==="+startTime); 

    request.setAttribute("startTime", startTime);

    return true;
}

//after the handler is executed
 @Override
public void postHandle(
    HttpServletRequest request, HttpServletResponse response, 
    Object handler, ModelAndView modelAndView)
    throws Exception {

    long startTime = (Long)request.getAttribute("startTime");

    long endTime = System.currentTimeMillis();

    long executeTime = endTime - startTime;

    System.out.println("postHandle executeTime==="+executeTime);

    //modified the exisitng modelAndView
    //modelAndView.addObject("executeTime",executeTime);
    //user3563589

    //log it
    if(logger.isDebugEnabled()){
       logger.debug("[" + handler + "] executeTime : " + executeTime + "ms");
    }
}

 @Override
    public void afterCompletion(HttpServletRequest request,
            HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
     long startTime = (Long)request.getAttribute("startTime");

        long endTime = System.currentTimeMillis();

        long executeTime = endTime - startTime;

        System.out.println("afterCompletion executeTime==="+executeTime);

        request.setAttribute("executeTime", String.valueOf(executeTime));

        System.out.println("After completion handle");
    }

}

答案 1 :(得分:0)

在您当前的要求中,计算方法执行时间是您的交叉关注

所以使用Spring AOP会很有用, 使用AOP API中的周围建议

围绕建议是Spring AOP中最强大的建议。原因是,此建议可以在方法调用之前和之后执行自定义行为。

我推荐你看下面的链接。

http://www.compiletimeerror.com/2013/05/spring-aop-around-advice-example.html#.U1efO6IUBCw