+ ---- SPRINGMVC execution flow underlying analytical

SpringMVC flowchart as shown above, according to the figure, at the bottom of the source in series:

  1. Locate doDisPatch in the DispatcherServlet

  

  2. Observe the method body, then find getHandler method

  

 

 

   3. point into the method, also found that calls another method getHandler

  

  4. The click-through method, an interface is found, then we enter the abstract class AbstractHandlerMappingof getHandler Method:

  

  

  5. Check getHandlerExecutionChain method 

复制代码
protected HandlerExecutionChain getHandlerExecutionChain(Object handler, HttpServletRequest request) {
    //如果不是chain类型,将handler作为构造函数创建一个chain实例
    HandlerExecutionChain chain = (handler instanceof HandlerExecutionChain ?
                                   (HandlerExecutionChain) handler : new HandlerExecutionChain(handler));
 
    //获得有效url路径,用于匹配拦截器规则
    String lookupPath = this.urlPathHelper.getLookupPathForRequest(request);
    //获取所有拦截器
    for (HandlerInterceptor interceptor : this.adaptedInterceptors) {
        //如果是MappedInterceptor类型的,按照规则看看当前拦截器是否需要加入拦截
        if (interceptor instanceof MappedInterceptor) {
            MappedInterceptor mappedInterceptor = (MappedInterceptor) interceptor;
            //如果拦截器规则设置/*,表示拦截所有,也就是说url是什么都会加入
            if (mappedInterceptor.matches(lookupPath, this.pathMatcher)) {
                chain.addInterceptor(mappedInterceptor.getInterceptor());
            }
        }
        else {
            //该拦截器直接加入拦截器链
            chain.addInterceptor(interceptor);
        }
    }
    return chain;
复制代码

  6.返回到DispatcherServlet,这样我们知道getHandler方法就是通过HandlerMapping(处理映射器)返回一个处理链,处理链中包含了n个拦截(上面代码详解)

  

  7.进入getHandlerAdapter方法

  

  这里回忆一下默认的Adapter实现有哪些:

org.springframework.web.servlet.HandlerAdapter=org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter,\
    org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter,\
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter

  其中前两个Adapter都跟我们当前的例子没关系,怎么看出来的呢?回到getHandlerAdapter方法中,接下来会遍历Adapter列表,依此调用supports方法查询与当前handler是否支持。其上两个Adapter一个是处理HttpRequestHandler,一个是处理Controller类的,只有最后一个RequestMappingHandlerAdaptersupports方法才是我们要的

   8.进入RequestMappingHandlerAdapter

  

  

 

   此时看到上面两个方法,便一切都能说通了,如下图:

  

 

   9.这一步,我们知道中央调度器将处理链交给处理器适配器进行处理器Handler的匹配,从而调用Controller的方法,返回ModelAndView,交给中央调度器 ,然后进行下面的视图解析,渲染视图等

Guess you like

Origin www.cnblogs.com/lowerma/p/11826657.html