1

我是 Spring MVC 的新手,我的任务是计算 Spring MVC 中的每一次点击。我能够在 Servlet 中实现这一点。但不知道如何在春季实现这一目标。有没有办法跟踪每个请求?提前致谢。

4

3 回答 3

2

试试这样的拦截器

public class RequesInterceptor extends HandlerInterceptorAdapter {
    private static Object lock = new Object();
    private static int count =  0

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws ServletException {
        synchronize(lock){
            count++;
        }
    }

}
于 2017-11-07T08:10:11.987 回答
1

尝试以下代码

1)使用同步静态方法。

    public class RequestProcessingInterceptor extends HandlerInterceptorAdapter {

        private static int count = 0;

        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
                throws Exception {
            incrementCount();
            return true;
        }

        public static synchronized void incrementCount() {
            count++;
            System.out.println("[requestCount]" + count);
        }
}

2)使用原子整数

    public class RequestProcessingInterceptor extends HandlerInterceptorAdapter {

    private final static AtomicInteger count = new AtomicInteger(0);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        count.incrementAndGet();

        System.out.println("[---count---]" + count);

        return true;
    }
}
于 2017-11-07T08:41:58.490 回答
0

正如其他人所说,您应该使用拦截器:

1)在你的 dispatcher-servlet.xml 添加:

<mvc:interceptor>
  <mvc:mapping path="/**" />
  <bean class="xx.xx.xx.handlers.ViewInterceptor" />
</mvc:interceptor>

2)拦截器java代码:

@Service
public class ViewInterceptor extends HandlerInterceptorAdapter{
      @Override
      public boolean preHandle(HttpServletRequest request, HttpServletResponse 
            response, Object handler) throws Exception {
      ... do some  pre stuff
  }

  public void postHandle(HttpServletRequest request, 
                        HttpServletResponse response, 
                        Object handler, 
                        ModelAndView model) throws Exception {
  ... do some post stuff
  }

}

于 2017-11-07T09:18:43.707 回答