springmvc拦截器的配置使用:
自定义监听器实现HandlerInterceptor接口:
在springmvc的配置文件中引入自定义拦截器对象及拦截目标
拦截器的方法调用
自定义一个拦截器:
@Component public class LoginInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("成功执行"); return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("测试方法在控制器执行顺序的前后"); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("测试方法在控制器执行转发完毕或者结束后调用关闭资源"); } }
自定义一个拦截目标:
拦截器及控制器方法的执行顺序:
注意:
preHandle方法执行返回值为false时,拦截此请求
default boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { return true; }
异常拦截器:
局部异常拦截器:
加在controller中,只针对此控制器对象有效
全局异常拦截器: