继上一篇 【深入浅出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
没有重写 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 mvc的问题都集中再这块。
@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
实现前后端交互
@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
适配的