前言
继上一篇【深入浅出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
适配的