1.实现拦截器:
a)java类实现HandlerInterceptor接口
public class MyInterceptor implements HandlerInterceptor { //在请求处理的方法执行之前执行 //如果返回true那么执行下一个拦截器,如果返回false那么不执行下一个拦截器 @Override public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception { System.out.println("--------------处理前--------------"); return true; } //在请求处理的方法执行之后执行 @Override public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception { System.out.println("--------------处理后-------------"); } //在DispatcherServlet处理后执行----执行清理工作 @Override public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception { } }
b)配置拦截器
<!--拦截器配置--> <mvc:interceptors> <mvc:interceptor> <!-- /**包括路径及其子路径 /admin/* - 拦截的是/admin/add,/admin/list 等 /admin/user/add不会被拦截 /admin/** 上面的这些都会被拦截 --> <mvc:mapping path="/**"/> <!--对应的拦截器--> <bean class="com.app.interceptor.MyInterceptor"></bean> </mvc:interceptor> </mvc:interceptors>