SpringMVC是怎么处理请求的?

SpringMVC是怎么处理请求的?

SpringMVC实现了传统的javax.servlet,将一系列请求过程中非业务的内容进行封装,使我们可以专注于业务的开发,那么它是怎么进行封装的?

DispatcherServlet

这是SpringMVC实现的的Servlet,也是它处理请求最核心的类,整个请求的处理流程都可以通过分析这个类了解清楚。

这是DispatcherServlet的继承关系图:

image59.png

HttpServletBean覆写了init方法,对初始化过程做了一些处理

public final void init() throws ServletException {
        PropertyValues pvs = new ServletConfigPropertyValues(getServletConfig(), this.requiredProperties);
        if (!pvs.isEmpty()) {
            try {
                BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this);
                ResourceLoader resourceLoader = new ServletContextResourceLoader(getServletContext());
                bw.registerCustomEditor(Resource.class, new ResourceEditor(resourceLoader, getEnvironment()));
                initBeanWrapper(bw);
                bw.setPropertyValues(pvs, true);
            }
            catch (BeansException ex) {
                if (logger.isErrorEnabled()) {
                    logger.error("Failed to set bean properties on servlet '" + getServletName() + "'", ex);
                }
                throw ex;
            }
        }

        initServletBean();
    }

其中ServletConfigPropertyValues会利用ServletConfig对象从web.xml中突出配置参数,并设置到ServletConfigPropertyValues中。
initServletBean()在子类FrameworkServlet中被实现:

protected final void initServletBean() throws ServletException {
    this.webApplicationContext = initWebApplicationContext();
    initFrameworkServlet();
}

它最重要的是初始化了webApplicationContext,这是Spring容器上下文,通过FrameworkServlet后,Servlet和Spring容器就关联起来了,initFrameworkServlet()供子类复写做一些需要的处理。

请求处理过程

DispatcherServlet通过onDispatch方法来处理每个请求,核心流程通过以下代码来体现:

protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpServletRequest processedRequest = request;
        HandlerExecutionChain mappedHandler = null;

        WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);

        try {
            ModelAndView mv = null;
            Exception dispatchException = null;

            try {
                processedRequest = checkMultipart(request);

                // Determine handler for the current request.
                mappedHandler = getHandler(processedRequest); // 步骤一

                // Determine handler adapter for the current request.
                HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());  //步骤二

                if (!mappedHandler.applyPreHandle(processedRequest, response)) { //步骤三
                    return;
                }

                // Actually invoke the handler.
                mv = ha.handle(processedRequest, response, mappedHandler.getHandler()); //步骤四
  
                mappedHandler.applyPostHandle(processedRequest, response, mv); //步骤五
            }

            processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException); //步骤六
        }
    }

  • 步骤一:通过this.handlerMappings找到HandlerExecutionChain,而在HandlerExecutionChain内部包装了拦截器HandlerInterceptor
  • 步骤二:遍历this.handlerAdapters集合,通过HandlerExecutionChain中的Handler来找到支持此Handler的HandlerAdapter
  • 步骤三:调用HandlerInterceptor的preHandle方法做前置处理
  • 步骤四:通过HandlerAdapter的handle方法得到ModeAndView
  • 步骤五:调用HandlerInterceptor的postHandle方法做后置处理
  • 步骤六:调用processDispatchResult对ModeAndView做处理,同时,在上面步骤中发生的异常也一并在processDispatchResult中处理,最终异常会被HandlerExceptionResolver处理掉;接着processDispatchResult继续处理ModeAndView,调用ViewResolver的resolveViewName得到View对象,接着调用View的render方法得到最终的结果,在render方法中传入了Response作为参数,便于接收最终的结果

以上六个步骤就是SpringMVC处理请求的核心流程,在每个流程中还有很多细节。

image60.png

请求处理方法的查找

在AbstractHandlerMethodMapping的initHandlerMethods中:

protected void initHandlerMethods() {
        String[] beanNames = (this.detectHandlerMethodsInAncestorContexts ?
                BeanFactoryUtils.beanNamesForTypeIncludingAncestors(getApplicationContext(), Object.class) :
                getApplicationContext().getBeanNamesForType(Object.class));

        for (String beanName : beanNames) {
            if (!beanName.startsWith(SCOPED_TARGET_NAME_PREFIX)) {
                Class<?> beanType = null;
                try {
                    beanType = getApplicationContext().getType(beanName);
                }
                catch (Throwable ex) {
                    // An unresolvable bean type, probably from a lazy bean - let's ignore it.
                    if (logger.isDebugEnabled()) {
                        logger.debug("Could not resolve target class for bean with name '" + beanName + "'", ex);
                    }
                }
                if (beanType != null && isHandler(beanType)) {
                    detectHandlerMethods(beanName);
                }
            }
        }
        handlerMethodsInitialized(getHandlerMethods());
    }

protected boolean isHandler(Class<?> beanType) {
    return (AnnotatedElementUtils.hasAnnotation(beanType, Controller.class) ||
            AnnotatedElementUtils.hasAnnotation(beanType, RequestMapping.class));
}

先找到Spring容器初始化时的所有bean的名字,然后遍历这些名字,通过isHandler来判断这些bean是否@Controller和@RequestMapping修饰,有的话执行detectHandlerMethods方法。

    protected void detectHandlerMethods(final Object handler) {
        Class<?> handlerType = (handler instanceof String ?
                getApplicationContext().getType((String) handler) : handler.getClass());
        final Class<?> userType = ClassUtils.getUserClass(handlerType);

        Map<Method, T> methods = MethodIntrospector.selectMethods(userType,
                new MethodIntrospector.MetadataLookup<T>() {
                    @Override
                    public T inspect(Method method) {
                        try {
                            return getMappingForMethod(method, userType);
                        }
                        catch (Throwable ex) {
                            throw new IllegalStateException("Invalid mapping on handler class [" +
                                    userType.getName() + "]: " + method, ex);
                        }
                    }
                });

        if (logger.isDebugEnabled()) {
            logger.debug(methods.size() + " request handler methods found on " + userType + ": " + methods);
        }
        for (Map.Entry<Method, T> entry : methods.entrySet()) {
            Method invocableMethod = AopUtils.selectInvocableMethod(entry.getKey(), userType);
            T mapping = entry.getValue();
            registerHandlerMethod(handler, invocableMethod, mapping);
        }
    }

在detectHandlerMethods方法中,核心的是getMappingForMethod和registerHandlerMethod这两个方法,getMappingForMethod在子类RequestMappingHandlerMapping中实现:

protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) {
    RequestMappingInfo info = createRequestMappingInfo(method);
    if (info != null) {
        RequestMappingInfo typeInfo = createRequestMappingInfo(handlerType);
        if (typeInfo != null) {
            info = typeInfo.combine(info);
        }
    }
    return info;
}

它先查找方法的@RequestMapping注解,然后再查找类的@RequestMapping注解,如果都存在的话执行合并操作,最终会合并成一个RequestMappingInfo。

一些核心类

HandlerMethod

一个封装了Method和Parameter的辅助类,在HandlerMapping中构造,在HandlerAdapter中消费。

// class AbstractHandlerMethodMapping

private static final HandlerMethod PREFLIGHT_AMBIGUOUS_MATCH =
        new HandlerMethod(new EmptyHandler(), ClassUtils.getMethod(EmptyHandler.class, "handle"));

// class AbstractHandlerMethodAdapter

public final boolean supports(Object handler) {
    return (handler instanceof HandlerMethod && supportsInternal((HandlerMethod) handler));
}

public final long getLastModified(HttpServletRequest request, Object handler) {
    return getLastModifiedInternal(request, (HandlerMethod) handler);
}

RequestMappingHandlerAdapter

HandlerAdapter的核心继承类,内部的HandlerMethodArgumentResolver和HandlerMethodReturnValueHandler分别负责对方法参数的解析和方法返回值的处理。比如HandlerMethodArgumentResolver的子类RequestParamMethodArgumentResolver处理@RequestParam参数的解析;HandlerMethodReturnValueHandler的子类ModelAndViewMethodReturnValueHandler处理ModeAndView的返回;在它们两共同的实现类RequestResponseBodyMethodProcessor中,处理@RequestBody注解的解析和@ResponseBody参数的返回等。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,847评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,208评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,587评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,942评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,332评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,587评论 1 218
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,853评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,568评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,273评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,542评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,033评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,373评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,031评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,073评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,830评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,628评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,537评论 2 269

推荐阅读更多精彩内容