示例如下:
在“springmvc简单构建一个项目(一)”的基础上增加以下这些:
?
1.自定义拦截器
class="java">package com.zgw.springmvc; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; /** * 实现HandlerInterceptor接口或继承HandlerInterceptorAdapter * 来实现自定义拦截器 * @author zan * */ public class InterceptorDemo implements HandlerInterceptor{ //请求前执行 @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { long startTime = System.currentTimeMillis(); request.setAttribute("startTime", startTime); return true; } //请求发生后执行 @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { long startTime = (Long) request.getAttribute("startTime"); request.removeAttribute("startTime"); long endTime = System.currentTimeMillis(); System.out.println("本次请求时间为:" + new Long(endTime - startTime)+"ms"); request.setAttribute("handlingTime", endTime - startTime); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { } }
?2.配置,在MySpringmvcConfig类中添加:
?
/* * 配置拦截器的Bean */ @Bean public InterceptorDemo interceptor() { return new InterceptorDemo(); } /* * 重写addInterceptors方法,注册一个拦截器 */ @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(interceptor()); }
?
3.运行,访问http://localhost:8080/springmvc_withoutwebxml/index,结果如下:
?
?
?
?
?
?
?
?
?
?
?
????????
??
?
?
?