美文网首页
Springboot Interceptor拦截器配置了excl

Springboot Interceptor拦截器配置了excl

作者: 尼古拉黑 | 来源:发表于2017-11-27 17:33 被阅读0次

    今天在配置interceptor时,配置了excludePath,但不知为何,死活就不生效,百度了半小时,都是在教怎么配置,看了几个方法一一照作,无奈怎么都无法生效,没办法了,只能跟一下代码看看到底怎么回事。

    首先spring的核心DispatcherServlet是跑不脱的,第一个断点就打在doDispatch方法了,既然是拦截器,那我得找找handler相关的信息,大家都知道spring的拦截器是链式结构,即HandlerExecutionChain这个关键类,这里是拦截器链容器

    代码走到1016行,突然发现问题可能出在这里:

    mappedHandler = getHandler(processedRequest);

    没有问题,这里正是构建拦截器链的地方,F5进去

    protected HandlerExecutionChaingetHandler(HttpServletRequest request)throws Exception {

    if (this.handlerMappings !=null) {

    for (HandlerMapping mapping :this.handlerMappings) {

    HandlerExecutionChain handler = mapping.getHandler(request);

            if (handler !=null) {

    return handler;

            }

    }

    }

    return null;

    }

    注意看这一段:HandlerExecutionChain handler = mapping.getHandler(request);

    开始构造拦截器链,一路跟踪进入AbstractHandlerMapping.getHandlerExecutionChain(),终于看见最后的关键环节:

    protected HandlerExecutionChaingetHandlerExecutionChain(Object handler, HttpServletRequest request) {

    HandlerExecutionChain chain = (handlerinstanceof HandlerExecutionChain ?

    (HandlerExecutionChain) handler :new HandlerExecutionChain(handler));

      String lookupPath =this.urlPathHelper.getLookupPathForRequest(request, LOOKUP_PATH);

      for (HandlerInterceptor interceptor :this.adaptedInterceptors) {

    if (interceptorinstanceof MappedInterceptor) {

    MappedInterceptor mappedInterceptor = (MappedInterceptor) interceptor;

            if (mappedInterceptor.matches(lookupPath, this.pathMatcher)) {

    chain.addInterceptor(mappedInterceptor.getInterceptor());

            }

    }

    else {

    chain.addInterceptor(interceptor);

          }

    }

    return chain;

    }

    注意这一段:mappedInterceptor.matches(lookupPath, this.pathMatcher),正是在这里将我定义的拦截器加入到了链中,原因是我配置的路径加入servlet-contextPath,但实际上这里的lookupPath是去掉了servlet-contextPath的路径,所以我的拦截器一直无法生效。

    至此问题解决,以前真的很不想写文章,解决问题,能百度就百度,不能就自己解决,但近来发现百度问题很严重,一个问题前三页恨不得都是一样的解决方案,因为很大部分都是转载来转载去,没人去管这个答案到底有没有用

    我总在想,能否有一款搜索引擎,只收录一手资料,自动屏蔽转载,用户可以给无用的答案点灭,灭到一定次数就隐藏,减少大家被浪费的时间。

    相关文章

      网友评论

          本文标题:Springboot Interceptor拦截器配置了excl

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