【深入浅出spring】Spring MVC 流程解析 — HandlerAdapter

扫码关注公众号:Java 技术驿站

发送:vip
将链接复制到本浏览器,永久解锁本站全部文章

【公众号:Java 技术驿站】 【加作者微信交流技术,拉技术群】

前言

继上一篇【深入浅出spring】Spring MVC 流程解析 — HanndlerMapping介绍了handler mapping后,本文按照【深入浅出spring】Spring MVC 流程解析的分析流程,继续往下分析,介绍下HandlerAdapter相关的内容。

总流程

回顾下DispatcherServlet.doDispatch的代码:

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

            WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);

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

                try {
                    processedRequest = checkMultipart(request);
                    multipartRequestParsed = (processedRequest != request);

                    // Determine handler for the current request.
                    mappedHandler = getHandler(processedRequest);
                    if (mappedHandler == null) {
                        noHandlerFound(processedRequest, response);
                        return;
                    }

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

                    // Process last-modified header, if supported by the handler.
                    String method = request.getMethod();
                    boolean isGet = "GET".equals(method);
                    if (isGet || "HEAD".equals(method)) {
                        long lastModified = ha.getLastModified(request, mappedHandler.getHandler());
                        if (logger.isDebugEnabled()) {
                            logger.debug("Last-Modified value for [" + getRequestUri(request) + "] is: " + lastModified);
                        }
                        if (new ServletWebRequest(request, response).checkNotModified(lastModified) && isGet) {
                            return;
                        }
                    }

                    if (!mappedHandler.applyPreHandle(processedRequest, response)) {
                        return;
                    }

                    // Actually invoke the handler.
                    mv = ha.handle(processedRequest, response, mappedHandler.getHandler());

                    if (asyncManager.isConcurrentHandlingStarted()) {
                        return;
                    }

                    applyDefaultViewName(processedRequest, mv);
                    mappedHandler.applyPostHandle(processedRequest, response, mv);
                }
                catch (Exception ex) {
                    dispatchException = ex;
                }
                catch (Throwable err) {
                    // As of 4.3, we're processing Errors thrown from handler methods as well,
                    // making them available for @ExceptionHandler methods and other scenarios.
                    dispatchException = new NestedServletException("Handler dispatch failed", err);
                }
                processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException);
            }
            catch (Exception ex) {
                triggerAfterCompletion(processedRequest, response, mappedHandler, ex);
            }
            catch (Throwable err) {
                triggerAfterCompletion(processedRequest, response, mappedHandler,
                        new NestedServletException("Handler processing failed", err));
            }
            finally {
                if (asyncManager.isConcurrentHandlingStarted()) {
                    // Instead of postHandle and afterCompletion
                    if (mappedHandler != null) {
                        mappedHandler.applyAfterConcurrentHandlingStarted(processedRequest, response);
                    }
                }
                else {
                    // Clean up any resources used by a multipart request.
                    if (multipartRequestParsed) {
                        cleanupMultipart(processedRequest);
                    }
                }
            }
        }

从源码可以看到,17行根据request拿到对象HandlerExecutionChain(包含一个处理器 handler 如HandlerMethod 对象、多个 HandlerInterceptor 拦截器对象)后,就是24行根据handler获取对应的adapter,并在44行调用适配器的handler方法(适配器设计模式可以自行google了解),返回ModelAndView。详细看下getHandlerAdapter这个方法:

        protected HandlerAdapter getHandlerAdapter(Object handler) throws ServletException {
            if (this.handlerAdapters != null) {
                for (HandlerAdapter ha : this.handlerAdapters) {
                    if (logger.isTraceEnabled()) {
                        logger.trace("Testing handler adapter [" + ha + "]");
                    }
                    if (ha.supports(handler)) {
                        return ha;
                    }
                }
            }
            throw new ServletException("No adapter for handler [" + handler +
                    "]: The DispatcherServlet configuration needs to include a HandlerAdapter that supports this handler");
        }

和上文handler mapping的逻辑非常类似,遍历容器中的所有HandlerAdapter,然后判断是否支持适配此handler,这里的关键方法supports是接口HandlerAdapter中的方法,具体逻辑由其实现类决定。默认的HandlerAdapter的实现类有3种:

  • RequestMappingHandlerAdapter
  • HttpRequestHandlerAdapter
  • SimpleControllerHandlerAdapter

RequestMappingHandlerAdapter

适配哪类处理器

RequestMappingHandlerAdapter没有重写supports方法,即执行的是其父类AbstractHandlerMethodAdapter的方法,代码如下:

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

其中supportInternal由子类RequestMappingHandlerAdapter实现,直接返回常量true,故可以认为只要handler属于HandlerMethod类型,就由RequestMappingHandlerAdapter来适配。即RequestMappingHandlerAdapter适配类型为HandlerMethod的处理器,对应RequestMappingHandlerMapping

处理逻辑

RequestMappingHandlerAdapter的处理逻辑主要由handleInternal实现:

        protected ModelAndView handleInternal(HttpServletRequest request,
                HttpServletResponse response, HandlerMethod handlerMethod) throws Exception {

            ModelAndView mav;
            checkRequest(request);

            // Execute invokeHandlerMethod in synchronized block if required.
            if (this.synchronizeOnSession) {
                HttpSession session = request.getSession(false);
                if (session != null) {
                    Object mutex = WebUtils.getSessionMutex(session);
                    synchronized (mutex) {
                        mav = invokeHandlerMethod(request, response, handlerMethod);
                    }
                }
                else {
                    // No HttpSession available -> no mutex necessary
                    mav = invokeHandlerMethod(request, response, handlerMethod);
                }
            }
            else {
                // No synchronization on session demanded at all...
                mav = invokeHandlerMethod(request, response, handlerMethod);
            }

            if (!response.containsHeader(HEADER_CACHE_CONTROL)) {
                if (getSessionAttributesHandler(handlerMethod).hasSessionAttributes()) {
                    applyCacheSeconds(response, this.cacheSecondsForSessionAttributeHandlers);
                }
                else {
                    prepareResponse(response);
                }
            }

            return mav;
        }

可以看到,核心处理逻辑由方法invokeHandlerMethod实现,这块处理逻辑比较复杂,涉及输入参数的解析,返回数据的处理,后面一篇文章【深入浅出spring】Spring MVC 流程解析 — InvocableHandlerMethod会重点讲这块。之前在问答社区发现很多spring mvc的问题都集中再这块。

HttpRequestHandlerAdapter

适配哪类处理器

        @Override
        public boolean supports(Object handler) {
            return (handler instanceof HttpRequestHandler);
        }

源码很简单,适配类型为HttpRequestHandler的处理器

处理逻辑

        @Override
        @Nullable
        public ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler)
                throws Exception {

            ((HttpRequestHandler) handler).handleRequest(request, response);
            return null;
        }

处理逻辑也很简单,直接调用HttpRequestHandler.handleRequest方法,这里不是通过返回数据实现和前端交互,而是直接通过改写HttpServletResponse实现前后端交互

SimpleControllerHandlerAdapter

适配哪类处理器

        @Override
        public boolean supports(Object handler) {
            return (handler instanceof Controller);
        }

这里的Controller是一个接口,即所有实现Controller接口的类,SimpleControllerHandlerAdapter都适配

处理逻辑

    @Override
        @Nullable
        public ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler)
                throws Exception {

            return ((Controller) handler).handleRequest(request, response);
        }

HttpRequestHandlerAdapter类似,直接调用Controller.handleRequest,即具体实现类的handleRequest方法,然后支持直接返回数据来和前端交互。
handler_mapping_sample中的SimpleUrlController就是通过SimpleControllerHandlerAdapter适配的

附录

RequestMappingHandlerAdapter 类图

2019101710044\_1.png


来源:[]()

赞(0) 打赏
版权归原创作者所有,任何形式的转载请联系博主:daming_90:Java 技术驿站 » 【深入浅出spring】Spring MVC 流程解析 — HandlerAdapter

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏