美文网首页SpringBoot
spring-boot学习笔记之Web拦截器

spring-boot学习笔记之Web拦截器

作者: linking12 | 来源:发表于2016-01-20 15:44 被阅读12482次

    spring-boot在web层面使用了spring mvc的拦截器功能,并没有做其他处理,故我们只要熟悉mvc的拦截器,自然而然可以将拦截器加入到spring-boot上

    拦截器接口
    package org.springframework.web.servlet;  
    public interface HandlerInterceptor {  
        boolean preHandle(  
                HttpServletRequest request, HttpServletResponse response,   
                Object handler)   
                throws Exception;  
      
        void postHandle(  
                HttpServletRequest request, HttpServletResponse response,   
                Object handler, ModelAndView modelAndView)   
                throws Exception;  
      
        void afterCompletion(  
                HttpServletRequest request, HttpServletResponse response,   
                Object handler, Exception ex)  
                throws Exception;  
    }   
    

    我们可能注意到拦截器一个有3个回调方法,而一般的过滤器Filter才两个,这是怎么回事呢?马上分析。

    preHandle****:预处理回调方法,实现处理器的预处理(如登录检查),第三个参数为响应的处理器(如我们上一章的Controller实现);
    返回值:true表示继续流程(如调用下一个拦截器或处理器);
    false表示流程中断(如登录检查失败),不会继续调用其他的拦截器或处理器,此时我们需要通过response来产生响应;
    postHandle****:
    后处理回调方法,实现处理器的后处理(但在渲染视图之前),此时我们可以通过modelAndView(模型和视图对象)对模型数据进行处理或对视图进行处理,modelAndView也可能为null。
    afterCompletion****:整个请求处理完毕回调方法,即在视图渲染完毕时回调,如性能监控中我们可以在此记录结束时间并输出消耗时间,还可以进行一些资源清理,类似于try-catch-finally中的finally,但仅调用处理器执行链中preHandle返回true的拦截器的afterCompletion

    拦截运行图
    正常流程 中断流程

    中断流程中,比如是HandlerInterceptor2中断的流程(preHandle返回false),此处仅调用它之前拦截器的preHandle返回true的afterCompletion方法。

    DispatcherServlet内部工作:

    
    //doDispatch方法
    //1、处理器拦截器的预处理(正序执行)
    HandlerInterceptor[] interceptors = mappedHandler.getInterceptors();
    if (interceptors != null) {
        for (int i = 0; i < interceptors.length; i++) {
        HandlerInterceptor interceptor = interceptors[i];
            if (!interceptor.preHandle(processedRequest, response, mappedHandler.getHandler())) {
                //1.1、失败时触发afterCompletion的调用
                triggerAfterCompletion(mappedHandler, interceptorIndex, processedRequest, response, null);
                return;
            }
            interceptorIndex = i;//1.2、记录当前预处理成功的索引
    }
    }
    //2、处理器适配器调用我们的处理器
    mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
    //当我们返回null或没有返回逻辑视图名时的默认视图名翻译(详解4.15.5 RequestToViewNameTranslator)
    if (mv != null && !mv.hasView()) {
        mv.setViewName(getDefaultViewName(request));
    }
    //3、处理器拦截器的后处理(逆序)
    if (interceptors != null) {
    for (int i = interceptors.length - 1; i >= 0; i--) {
          HandlerInterceptor interceptor = interceptors[i];
          interceptor.postHandle(processedRequest, response, mappedHandler.getHandler(), mv);
    }
    }
    //4、视图的渲染
    if (mv != null && !mv.wasCleared()) {
    render(mv, processedRequest, response);
        if (errorView) {
            WebUtils.clearErrorRequestAttributes(request);
    }
    //5、触发整个请求处理完毕回调方法afterCompletion
    triggerAfterCompletion(mappedHandler, interceptorIndex, processedRequest, response, null);
    
    
    
    
    // triggerAfterCompletion方法
    private void triggerAfterCompletion(HandlerExecutionChain mappedHandler, int interceptorIndex,
                HttpServletRequest request, HttpServletResponse response, Exception ex) throws Exception {
            // 5、触发整个请求处理完毕回调方法afterCompletion (逆序从1.2中的预处理成功的索引处的拦截器执行)
            if (mappedHandler != null) {
                HandlerInterceptor[] interceptors = mappedHandler.getInterceptors();
                if (interceptors != null) {
                    for (int i = interceptorIndex; i >= 0; i--) {
                        HandlerInterceptor interceptor = interceptors[i];
                        try {
                            interceptor.afterCompletion(request, response, mappedHandler.getHandler(), ex);
                        }
                        catch (Throwable ex2) {
                            logger.error("HandlerInterceptor.afterCompletion threw exception", ex2);
                        }
                    }
                }
            }
        }
    
    
    
    spring boot添加拦截器
    • 方法一
    @SpringBootApplication
    public class Application {
    
        public static void main(String[] args) {
            SpringApplication application = new SpringApplication(Application.class);
            // application.addListeners(new ApplicationListenerEnvironmentPrepared());
            // application.addListeners(new ApplicationListenerFailed());
            // application.addListeners(new ApplicationListenerPrepared());
            // application.addListeners(new ApplicationListenerStarted());
            application.run(args);
        }
    
        @Configuration
        static class WebMvcConfigurer extends WebMvcConfigurerAdapter {
    
            public void addInterceptors(InterceptorRegistry registry) {
                registry.addInterceptor(new HandlerInterceptorAdapter() {
    
                    @Override
                    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                                             Object handler) throws Exception {
                        request.getContextPath();
                        System.out.println("interceptor====");
                        return true;
                    }
                }).addPathPatterns("/*");
            }
        }
    }
    
    • 方法二
    @Configuration
    public class WebMvcConfigurer extends WebMvcConfigurerAdapter {
    
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(new HandlerInterceptorAdapter() {
    
                @Override
                public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                                         Object handler) throws Exception {
                    System.out.println("interceptor====222");
                    return true;
                }
            }).addPathPatterns("/*");
        }
    }
    

    总结:只要能被springboot扫描到即可

    相关文章

      网友评论

        本文标题:spring-boot学习笔记之Web拦截器

        本文链接:https://www.haomeiwen.com/subject/acrlkttx.html