继上一篇【深刻浅出spring】Spring MVC 流程解析 -- HanndlerMapping介绍了handler mapping后,本文按照【深刻浅出spring】Spring MVC 流程解析的分析流程,继续往下分析,介绍下HandlerAdapter
相关的内容。前端
回顾下DispatcherServlet.doDispatch
的代码:ios
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
这个方法:git
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种:spring
RequestMappingHandlerAdapter
没有重写supports
方法,即执行的是其父类AbstractHandlerMethodAdapter
的方法,代码以下:segmentfault
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的问题都集中再这块。session
@Override public boolean supports(Object handler) { return (handler instanceof HttpRequestHandler); }
源码很简单,适配类型为HttpRequestHandler
的处理器mvc
@Override @Nullable public ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { ((HttpRequestHandler) handler).handleRequest(request, response); return null; }
处理逻辑也很简单,直接调用HttpRequestHandler.handleRequest
方法,这里不是经过返回数据实现和前端交互,而是直接经过改写HttpServletResponse
实现先后端交互app
@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
适配的