是Spring MVC的新手,我的任务是计算Spring MVC中的每一个命中。能够在Servlet中实现这一点。但不知道如何在春天实现这一目标。有没有办法跟踪每个请求?提前谢谢。
答案 0 :(得分: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++;
}
}
}
答案 1 :(得分: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)使用AtomicInteger
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;
}
}
答案 2 :(得分: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
}
}