程序园Java Blog

SpringMVC【四】HandlerInterceptor

2019-04-30  本文已影响0人  爪哇部落格

\color{red}{码字不易,欢迎大家转载,烦请注明出处;谢谢配合}

前面我们针对DispatcherServlet,HandlerMapping,HandlerAdapter进行了源码剖析,对MVC的流程有了一定的认识;HandlerInterceptor也贯穿在整个请求处理的过程中,本文将针对HandlerInterceptor的源码,以及用法进行研读。

调用流程

HandlerInterceptor接口

HandlerInterceptor

口说无凭,我们一起回顾一下,DispatcherServletdoDispatch方法,

applyPreHandle方法 applyPostHandle方法 afterCompletion方法

以上三个方法的调用都是由mappedHandler 即(HandlerExecutionChain)来完成的,我们来确认一下调用逻辑。

HandlerExecutionChain

注册流程

以上就是HandlerInterceptor 执行处理流程了,那么HandlerInterceptor是何时被注册的呢?又是如何注册的呢?

不知您是否还记得,之前我们讲过的HandlerMapping;即使忘了也没有关系,我们可以细心的回想的分析一下也可以得出结论;首先HandlerInterceptor数组/集合是HandlerExecutionChain 是成员变量,而HandlerMapping.getHandler()则正是用于获取HandlerExecutionChain对象;所以我们可以大胆的猜想HandlerInterceptor的也跟HandlerMapping有关。

AbstractHandlerMapping

AbstractHandlerMappingHandlerMapping 的核心抽象子类,其余子类的实现都是继承自AbstractHandlerMapping,而AbstractHandlerMapping在设计时,便考虑到interceptor的注册,那么是何时为添加进HandlerExecutionChain呢?

我们接着来看AbstractHandlerMapping的getHandler方法


getHandler 包装

我们一起梳理一下:

1.HandlerInterceptor实际是在DispatcherServlet的doDispatch方法中被调用
2.HandlerInterceptor在HandlerMapping子类对象被初始化时会初始化AbstractHandlerMapping的adaptedInterceptors成员变量
3.HandlerInterceptor在HandlerMapping在调用getHandler方法时被包装到HandlerExecutionChain中

使用方法

我们常用的使用方法有两种:

1.实现HandlerInterceptor接口

public class DemoInterceptor 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("渲染已结束");
    }
}

2.继承HandlerInterceptorAdapter抽象类

public class DemoInterceptor2 extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("请求处理之前2");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("请求已处理2");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("渲染已结束2");
    }
}

千万不要以为实现了HandlerInterceptor就完了,我们还需要配置HandlerInterceptor要拦截的路径;可以通过以下方式。

1.通过配置类来生效

package xin.sunce.spring.interceptor;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

@Configuration
public class InterceptorConfig extends WebMvcConfigurationSupport {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new DemoInterceptor()).addPathPatterns("/login");
        registry.addInterceptor(new DemoInterceptor2()).addPathPatterns("/**")
          .excludePathPatterns("/login");
    }
}

addPathPatterns配置拦截的地址,excludePathPatterns配置排除的地址

2.通过配置文件

 <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/**"/>
            <mvc:exclude-mapping path="/login"/>
            <bean id="interceptor" name="demoInterceptor" 
                class="xin.sunce.spring.interceptor.DemoInterceptor"/>
        </mvc:interceptor>
        <mvc:interceptor>
            <mvc:mapping path="/login"/>
            <bean id="interceptor2" name="demoInterceptor2" 
                class="xin.sunce.spring.interceptor.DemoInterceptor2"/>
        </mvc:interceptor>
    </mvc:interceptors>

注意:此方式与<mvc:annotation-driven/>配置有冲突,会导致 <mvc:interceptors>中的第一个<mvc:interceptor>无效

因为<mvc:annotation-driven/>实现时创建默认的HandlerMapping以及HandlerAdapter,在AbstractHandlerMapping注册时,BeanFactoryUtils的beansOfTypeIncludingAncestors方法处理如下:

public static <T> Map<String, T> beansOfTypeIncludingAncestors(ListableBeanFactory lbf, Class<T> type, boolean includeNonSingletons, boolean allowEagerInit) throws BeansException {
    Assert.notNull(lbf, "ListableBeanFactory must not be null");
    Map<String, T> result = new LinkedHashMap(4);
    result.putAll(lbf.getBeansOfType(type, includeNonSingletons, allowEagerInit));
    if (lbf instanceof HierarchicalBeanFactory) {
        HierarchicalBeanFactory hbf = (HierarchicalBeanFactory)lbf;
        if (hbf.getParentBeanFactory() instanceof ListableBeanFactory) {
          /**递归添加Bean**/
            Map<String, T> parentResult = beansOfTypeIncludingAncestors((ListableBeanFactory)hbf.getParentBeanFactory(), type, includeNonSingletons, allowEagerInit);
            parentResult.forEach((beanName, beanInstance) -> {
                /**beanName已存在则不添加**/
                if (!result.containsKey(beanName) && !hbf.containsLocalBean(beanName)) {
                    result.put(beanName, beanInstance);
                }

            });
        }
    }
    return result;
}

正是由于beanName已存在时,则不往result添加结果,会导致<mvc:annotation-driven/>与<mvc:interceptors>;置于<mvc:annotation-driven/>,<mvc:interceptors>标签是如何工作的可以参考org.springframework.web.servlet.config.MvcNamespaceHandler

总结

1.了解HandlerInterceptor在何时执行
2.清楚HandlerInterceptor是如何注册以及被包装到HandlerExecutionChain中
3.明白HandlerInterceptor的使用

上一篇下一篇

猜你喜欢

热点阅读