springMVC自定义拦截器的执行顺序即底层原理实现

springMVC自定义拦截器的执行顺序即底层原理实现,第1张

springMVC自定义拦截器的执行顺序即底层原理实现

首先自定义2个拦截器MyHandlerInterceptor1和MyHandlerInterceptor2

MyHandlerInterceptor1.java

//拦截器
public class MyHandlerInterceptor1 implements HandlerInterceptor {

    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("MyHandlerInterceptor1 preHandle handler = "+handler);
        return false;
    }

    
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("MyHandlerInterceptor1 postHandle handler = "+handler+ " modelAndView = "+ modelAndView);
    }

    
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("MyHandlerInterceptor1 afterCompletion handler = "+handler+" ex = "+ex);
    }
}

MyHandlerInterceptor2.java

//拦截器
public class MyHandlerInterceptor2 implements HandlerInterceptor {

    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("MyHandlerInterceptor2 preHandle handler = "+handler);
        return false;
    }

    
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("MyHandlerInterceptor2 postHandle handler = "+handler+ " modelAndView = "+ modelAndView);
    }

    
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("MyHandlerInterceptor2 afterCompletion handler = "+handler+" ex = "+ex);
    }
}

在dispatcher-servlet.xml配置文件中配置拦截器

    
    
        
            
            
        
        
            
            
        
    

两个自定义的拦截器的执行情况

关于拦截器放行的问题
第一种情况:MyHandlerInterceptor1 放行 MyHandlerInterceptor2 放行
MyHandlerInterceptor1 preHandle   return true
MyHandlerInterceptor2 preHandle   return true
MyHandlerInterceptor2 postHandle
MyHandlerInterceptor1 postHandle
MyHandlerInterceptor2 afterCompletion
MyHandlerInterceptor1 afterCompletion
第二种情况:MyHandlerInterceptor1 放行 MyHandlerInterceptor2 不放行
MyHandlerInterceptor1 preHandle  return true
MyHandlerInterceptor2 preHandle  return false
MyHandlerInterceptor1 afterCompletion
第三种情况:MyHandlerInterceptor1 不放行 MyHandlerInterceptor2 不放行
MyHandlerInterceptor1 preHandle  return false

对于第二种情况的底层代码解析

为什么会执行MyHandlerInterceptor1 afterCompletion

 

 所以会出现情况二的情况

不足之处敬请谅解!!!

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5684469.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存