Controller层的拦截器继承于HandlerInterceptorAdapter
HandlerInterceptorAdapter.java 代码如下
public abstract class HandlerInterceptorAdapter implements HandlerInterceptor { public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)throws Exception { return true; } public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)throws Exception {
} public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)throws Exception {
} }
Spring拦截器通过重写这三个方法实现Controller的拦截。
public class ControllerInterceptor extends HandlerInterceptorAdapter { public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("ControllerInterceptor.preHandle()"); return true; } public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("ControllerInterceptor.postHandle()"); } public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("ControllerInterceptor.afterCompletion()"); } }
配置拦截器
<bean id="handlerMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"> <property name="interceptors"> <list> <ref bean="controllerInterceptor" /> </list> </property> <property name="mappings"> <props> <prop key="/hao/hello.do">helloWorldController</prop> </props> </property> </bean> <bean id="controllerInterceptor" class="com.web.spring.mvc.interceptor.ControllerInterceptor"/>
测试代码HelloWorldController.java
@Controller @RequestMapping("/hao") public class HelloWorldController { @RequestMapping(value = "/hello") public String hello(HttpServletRequest request, HttpServletResponse response) { System.out.println("hello"); return "helloWorld"; } }
说明:
发起请求,进入拦截器链,运行所有拦截器的preHandle方法,
1.当preHandle方法返回false时,从当前拦截器往回执行所有拦截器的afterCompletion方法,再退出拦截器链。
2.当preHandle方法全为true时,执行下一个拦截器,直到所有拦截器执行完。再运行被拦截的Controller。然后进入拦截器链,运行所有拦截器的postHandle方法,完后从最后一个拦截器往回执行所有拦截器的afterCompletion方法.
当有拦截器抛出异常时,会从当前拦截器往回执行所有拦截器的afterCompletion方法