Spring Mvc执行流程(请求处理过程)...才发现写文档这么烦

一个服务进程拉起流程 摘取其中部分关键代码

//路径 -> NioEndpoint.Poller.run()
//轮询服务 如果的到的keyCount大于0表示有请求需要处理
keyCount = selector.select(selectorTimeout); 
//如果keyConut大于即存在任务就会从selectKeys中拿到迭代器
Iterator<SelectionKey> iterator = keyCount > 0 ? selector.selectedKeys().iterator() : null;
//循环遍历当前迭代器中的任务
while (iterator != null && iterator.hasNext()) {
   	SelectionKey sk = iterator.next();
    NioSocketWrapper socketWrapper = (NioSocketWrapper) sk.attachment();
    // Attachment may be null if another thread has called
    // cancelledKey()
    if (socketWrapper == null) {
        iterator.remove();
    } else {
        iterator.remove();
        //核心方法
        processKey(sk, socketWrapper);
    }
}
protected void processKey(SelectionKey sk, NioSocketWrapper socketWrapper) {
	try {
	    ...
        if (!closeSocket && sk.isWritable()) {
            if (socketWrapper.writeOperation != null) {
                if (!socketWrapper.writeOperation.process()) {
                    closeSocket = true;
                }
            //重点关注 processSocket 这个方法
            } else if (!processSocket(socketWrapper, SocketEvent.OPEN_WRITE, true)) {
                closeSocket = true;
            }
        }
        if (closeSocket) {
            cancelledKey(sk, socketWrapper);
        }
    }
    ...
}

重点分析 processSocket 方法

public boolean processSocket(SocketWrapperBase<S> socketWrapper,
            SocketEvent event, boolean dispatch) {
    try {
        if (socketWrapper == null) {
            return false;
        }
        SocketProcessorBase<S> sc = null;
        if (processorCache != null) {
            sc = processorCache.pop();
        }
        if (sc == null) {
        	//根据基本的一个方法执行 都会走到这里会创建一个SockerProcessor
            sc = createSocketProcessor(socketWrapper, event);
        } else {
            sc.reset(socketWrapper, event);
        }
        //获取一个执行器
        Executor executor = getExecutor();
        if (dispatch && executor != null) {
            //将创建的SocketProcessor对象即局部变量sc放入执行器执行任务
            //所以确定createSocketProcessor创建的一个SocketProcessBase<S> sc是实现了Runnable或者Thread接口的类(实际实现了Runnable)
            executor.execute(sc);
        } else {
            sc.run();
        }
    } 
    ...
    return true;
}

protected SocketProcessorBase<NioChannel> createSocketProcessor(
            SocketWrapperBase<NioChannel> socketWrapper, SocketEvent event) {
    //创建一个SocketProcessor 
    return new SocketProcessor(socketWrapper, event);
}

分析ScoketProcessor

下图为SocketProcessor的继承体系
在这里插入图片描述

//class - SocketProcessorBase实现的run方法
@Override
public final void run() {
    synchronized (socketWrapper) {
        // It is possible that processing may be triggered for read and
        // write at the same time. The sync above makes sure that processing
        // does not occur in parallel. The test below ensures that if the
        // first event to be processed results in the socket being closed,
        // the subsequent events are not processed.
        if (socketWrapper.isClosed()) {
            return;
        }
        doRun();//这个方法为子类的方法
    }
}

//class - SocketProcessor
protected void doRun() {
	NioChannel socket = socketWrapper.getSocket();
	SelectionKey key = socket.getIOChannel().keyFor(socket.getSocketWrapper().getPoller().getSelector());
	Poller poller = NioEndpoint.this.poller;
	if (poller == null) {
	    socketWrapper.close();
	    return;
	}
	try {
	    int handshake = -1;
	    try {
	        if (key != null) {
	            if (socket.isHandshakeComplete()) {
	                handshake = 0;
	            } else if (event == SocketEvent.STOP || event == SocketEvent.DISCONNECT||event == SocketEvent.ERROR) {
	                handshake = -1;
	            } else {
	                handshake = socket.handshake(key.isReadable(), key.isWritable());
	                event = SocketEvent.OPEN_READ;
	            }
	        }
	    } 
	    ...
	    if (handshake == 0) {
	        SocketState state = SocketState.OPEN;
	        // Process the request from this socket
	        if (event == null) {
	            state = getHandler().process(socketWrapper, SocketEvent.OPEN_READ);
	        } else {
	        	//调用此方法 - 后续会进入到DispatcherServlet(通过过滤器)
	            state = getHandler().process(socketWrapper, event);
	        }
	        if (state == SocketState.CLOSED) {
	            poller.cancelledKey(key, socketWrapper);
	        }
	    } else if (handshake == -1 ) {
	        poller.cancelledKey(key, socketWrapper);
	    } else if (handshake == SelectionKey.OP_READ){
	        socketWrapper.registerReadInterest();
	    } else if (handshake == SelectionKey.OP_WRITE){
	        socketWrapper.registerWriteInterest();
	    }
	} 
	...
	} finally {
	    socketWrapper = null;
	    event = null;
	    //return to cache
	    if (running && !paused && processorCache != null) {
	        processorCache.push(this);
	    }
	}
}

通过动态调试分析得知getHandler().process(socketWrapper,event) 最终会调用到

//class - AbstractProtocol
//(1)
public SocketState process(SocketWrapperBase<S> wrapper, SocketEvent status) {
	...
	do {
		//此方法为后续的入口
	    state = processor.process(wrapper, status);
	   	... 
	   	//后续代码暂时不做分析
	} while ( state == SocketState.UPGRADING);	
	...
}
//(2)
else if (status == SocketEvent.OPEN_READ) {
	state = service(socketWrapper);
}
//(3)
getAdapter().service(request, response);
//(4)
connector.getService().getContainer().getPipeline().getFirst().invoke(request, response);
//(5)
host.getPipeline().getFirst().invoke(request, response);
//(6)
getNext().invoke(request, response);
...
//过滤器执行链
filterChain.doFilter(request.getRequest(), response.getResponse());
//最终执行到类ApplicationFilterChain中的internalDoFilter方法中调用
servlet.service(request, response);

通过Servlet规范可知到这里就是正常的开发流程后续会根据请求头中的Get Post Put Delete Header等进行不同的处理次数由于在浏览器直接执行的一个get请求所以会直接到doGet的判断中进行后续的执行

//abstract class - HttpServlet
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	//获取请求类型
	String method = req.getMethod();
	if (method.equals(METHOD_GET)) {
	    long lastModified = getLastModified(req);
	    if (lastModified == -1) {
	    	//进行doGet方法进行后续的调用    
	        doGet(req, resp);
	...
}
//abstract class - FrameworkServlet(已经到了webMvc的包中了)
protected final void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		processRequest(request, response);
}


protected final void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
...//(获取一些上下文变量和请求属性等)
try {
	doService(request, response);
}
...
}

//class DispatcherServlet - doServer方法主要是要调用doDispatch方法进行请求分发
protected void doService(HttpServletRequest request, HttpServletResponse response) throws Exception {
	...
	request.setAttribute(WEB_APPLICATION_CONTEXT_ATTRIBUTE, getWebApplicationContext());
	request.setAttribute(LOCALE_RESOLVER_ATTRIBUTE, this.localeResolver);
	request.setAttribute(THEME_RESOLVER_ATTRIBUTE, this.themeResolver);
	request.setAttribute(THEME_SOURCE_ATTRIBUTE, getThemeSource());

	if (this.flashMapManager != null) {
		FlashMap inputFlashMap = this.flashMapManager.retrieveAndUpdate(request, response);
		if (inputFlashMap != null) {
			request.setAttribute(INPUT_FLASH_MAP_ATTRIBUTE, Collections.unmodifiableMap(inputFlashMap));
		}
		request.setAttribute(OUTPUT_FLASH_MAP_ATTRIBUTE, new FlashMap());
		request.setAttribute(FLASH_MAP_MANAGER_ATTRIBUTE, this.flashMapManager);
	}

	RequestPath previousRequestPath = null;//获取上一个请求路径
	if (this.parseRequestPath) {
		previousRequestPath = (RequestPath) request.getAttribute(ServletRequestPathUtils.PATH_ATTRIBUTE);
		ServletRequestPathUtils.parseAndCache(request);
	}

	try {
		//进行请求分发
		doDispatch(request, response);
	}
	finally {
		if (!WebAsyncUtils.getAsyncManager(request).isConcurrentHandlingStarted()) {
			// Restore the original attribute snapshot, in case of an include.
			if (attributesSnapshot != null) {
				restoreAttributesAfterInclude(request, attributesSnapshot);
			}
		}
		if (this.parseRequestPath) {
			ServletRequestPathUtils.setParsedRequestPath(previousRequestPath, request);
		}
	}
}

到doDispatch方法之后 后续就是处理Spring Mvc的核心处理了(包括判断当前请求是否是一个文件请求,获取请求处理器,获取处理适配器,以及拦截器的调用preHandle方法的调用和PostHandler方的调用)具体代码如下

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 {
			/*
			检查当前请求是否是一个文件请求(判断请求头中的是的ContentType是否是以"multipart/form-data"或者"multipart/"开始,
			如果是最后会由MultipartResolver文件解析器解析请求并返回一个 MultipartHttpServletRequest接口的实现类)
			*/
			processedRequest = checkMultipart(request);
			//判断不相等则是一个文件请求
			multipartRequestParsed = (processedRequest != request);
			//获取请求处理器 - 后续分析(重点)
			mappedHandler = getHandler(processedRequest);
			if (mappedHandler == null) {
				noHandlerFound(processedRequest, response);
				return;
			}
			//适配器
			HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());
			//获取请求方法
			String method = request.getMethod();
			boolean isGet = HttpMethod.GET.matches(method);
			if (isGet || HttpMethod.HEAD.matches(method)) {
				long lastModified = ha.getLastModified(request,mappedHandler.getHandler());
				if (new ServletWebRequest(request,response).checkNotModified(lastModified) && isGet) {
					return;
				}
			}
			//拦截器的前置请求处理
			if (!mappedHandler.applyPreHandle(processedRequest, response)) {
				return;
			}
			//真正调用处理方法(会进行请求参数的解析处理,@RequestMapping,@PathVariable等的解析)
			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);
			}
		}
	}
}

上述代码是一个请求从tomcat容器到整个spring mvc的处理过程代码下面 就来慢慢分析spring mvc处理过程中的部分重要代码

-----------------------------------------------------------------------------------------------------------------

1 getHandler(processdRequst)方法

protected HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
	if (this.handlerMappings != null) {
		//增强for循环从handlerMappings中获取到处理器(具体处理器怎样填充到handlerMappings中后续在分析)
		for (HandlerMapping mapping : this.handlerMappings) {
			HandlerExecutionChain handler = mapping.getHandler(request);
			if (handler != null) {
				return handler;
			}
		}
	}
	return null;
}

1.1 handlerMappings中的处理器列表

在这里插入图片描述

1.2 HandlerExecutionChain handler = mapping.getHandler(request) 内部代码

public final HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
	//获取最佳处理方法HandlerMethod
	Object handler = getHandlerInternal(request);
	if (handler == null) {
		handler = getDefaultHandler();
	}
	if (handler == null) {
		return null;
	}
	// Bean name or resolved handler?
	if (handler instanceof String) {
		String handlerName = (String) handler;
		handler = obtainApplicationContext().getBean(handlerName);
	}
	
	// Ensure presence of cached lookupPath for interceptors and others
	if (!ServletRequestPathUtils.hasCachedPath(request)) {
		initLookupPath(request);
	}
	//添加拦截器
	HandlerExecutionChain executionChain = getHandlerExecutionChain(handler, request);
	
	if (logger.isTraceEnabled()) {
		logger.trace("Mapped to " + handler);
	}
	else if (logger.isDebugEnabled() && !DispatcherType.ASYNC.equals(request.getDispatcherType())) {
		logger.debug("Mapped to " + executionChain.getHandler());
	}
	
	if (hasCorsConfigurationSource(handler) || CorsUtils.isPreFlightRequest(request)) {
		CorsConfiguration config = getCorsConfiguration(handler, request);
		if (getCorsConfigurationSource() != null) {
			CorsConfiguration globalConfig = getCorsConfigurationSource().getCorsConfiguration(request);
			config = (globalConfig != null ? globalConfig.combine(config) : config);
		}
		if (config != null) {
			config.validateAllowCredentials();
		}
		executionChain = getCorsHandlerExecutionChain(request, executionChain, config);
	}
	//返回已经添加了拦截器的一个执行链(HandlerExecutionChain)
	return executionChain;
}
	| //获取HandlerMethod - 包含处理当前请求方法的一个类
	V
Object handler = getHandlerInternal(request);
	|
	V
protected HandlerMethod getHandlerInternal(HttpServletRequest request) throws Exception {
	request.removeAttribute(PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE);
	try {
		return super.getHandlerInternal(request);
	}
	finally {
		ProducesRequestCondition.clearMediaTypesAttribute(request);
	}
}
	|
	V
protected HandlerMethod getHandlerInternal(HttpServletRequest request) throws Exception {
	//获取请求路径
	String lookupPath = initLookupPath(request);
	//获取读锁并上锁
	this.mappingRegistry.acquireReadLock();
	try {
		HandlerMethod handlerMethod = lookupHandlerMethod(lookupPath, request);
		return (handlerMethod != null ? handlerMethod.createWithResolvedBean() : null);
	}
	finally {
		//释放锁
		this.mappingRegistry.releaseReadLock();
	}
}

	|
	V
protected HandlerMethod lookupHandlerMethod(String lookupPath, HttpServletRequest request) throws Exception {
	List<Match> matches = new ArrayList<>();
	//获取一个RequestMappingInfo对象 对象包含请求路径
	List<T> directPathMatches = this.mappingRegistry.getMappingsByDirectPath(lookupPath);
	if (directPathMatches != null) {
		//从mappingRegistry中获取对应的MappingRegistration并创建一个Match对象添加到成员matches中
		addMatchingMappings(directPathMatches, matches, request);
	}
	if (matches.isEmpty()) {
		addMatchingMappings(this.mappingRegistry.getRegistrations().keySet(), matches, request);
	}
	if (!matches.isEmpty()) {
		Match bestMatch = matches.get(0);
		if (matches.size() > 1) {
			//当在添加matches过程中超过了2个则会调用这里最终会抛出一个异常(OPTIONS方法并且请求头中包含ORIGIN和Access-Control-Request-Method属性则不会抛出异常)
			Comparator<Match> comparator = new MatchComparator(getMappingComparator(request));
			matches.sort(comparator);
			bestMatch = matches.get(0);
			if (logger.isTraceEnabled()) {
				logger.trace(matches.size() + " matching mappings: " + matches);
			}
			if (CorsUtils.isPreFlightRequest(request)) {
				for (Match match : matches) {
					if (match.hasCorsConfig()) {
						return PREFLIGHT_AMBIGUOUS_MATCH;
					}
				}
			}
			else {
				Match secondBestMatch = matches.get(1);
				if (comparator.compare(bestMatch, secondBestMatch) == 0) {
					Method m1 = bestMatch.getHandlerMethod().getMethod();
					Method m2 = secondBestMatch.getHandlerMethod().getMethod();
					String uri = request.getRequestURI();
					throw new IllegalStateException(
							"Ambiguous handler methods mapped for '" + uri + "': {" + m1 + ", " + m2 + "}");
				}
			}
		}
		//设置属性 并与 最佳处方法进行绑定
		request.setAttribute(BEST_MATCHING_HANDLER_ATTRIBUTE, bestMatch.getHandlerMethod());
		handleMatch(bestMatch.mapping, lookupPath, request);
		//返回匹配到的HandlerMethod
		return bestMatch.getHandlerMethod();
	}
	else {
		return handleNoMatch(this.mappingRegistry.getRegistrations().keySet(), lookupPath, request);
	}
}

上述流程为通过请求路径获取到当前请求的处理器执行链(HandlerExecutionChain)其中包含当前请求的真正处理方法以及springmvc的拦截器

2 分析getHandlerAdapter(mapperHandler.getHandler())方法 - 得到一个适配器

下图为spring mvc的适配器列表(这些适配器的加载都可以在WebMvcAutoConfiguration中看到加载方式)
在这里插入图片描述

2.1 获取HandlerAdaptor的判断

protected HandlerAdapter getHandlerAdapter(Object handler) throws ServletException {
	if (this.handlerAdapters != null) {
		//增强for循环 从加载的所有的adaptor中循环拿出每一个并调用其supports方法进行判断
		for (HandlerAdapter adapter : this.handlerAdapters) {
			//根据动态分析找到的第一个RequestMappingHandlerAdapter就是支持当前HandlerMethod适配器
			//其余的不做分析,感兴趣的可以自己跟到这里进行源码的动态分析或者静态源码分析
			if (adapter.supports(handler)) {
				return adapter;
			}
		}
	}
	throw new ServletException("No adapter for handler [" + handler +
			"]: The DispatcherServlet configuration needs to include a HandlerAdapter that supports this handler");
}

//可以看到首先判断handler是否是一个HandlerMethod类,supportsInternal((HandlerMethod) handler)内部直接返回true
public final boolean supports(Object handler) {
	return (handler instanceof HandlerMethod && supportsInternal((HandlerMethod) handler));
}

3 拦截器的方法调用

//拦截器的前置处理调用 - 对象mapperHandler在前面getHandler的地方已经添加过过滤器所有这里直接调用并进行拦截器的前置处理
if (!mappedHandler.applyPreHandle(processedRequest, response)) {
	return;
}

boolean applyPreHandle(HttpServletRequest request, HttpServletResponse response) throws Exception {
	/*
	从拦截器列表中循环获取所有的拦截器并调用预处理方法,当有拦截器的预处理方法返回false时 
	在if内的代码块会被执行最后的结果就是不会继续进行后续的处理而直接返回给前端
	*/
	for (int i = 0; i < this.interceptorList.size(); i++) {
		HandlerInterceptor interceptor = this.interceptorList.get(i);
		//preHandle返回false 会直接返回false 外层会直接return
		if (!interceptor.preHandle(request, response, this.handler)) {
			triggerAfterCompletion(request, response, null);
			return false;
		}
		this.interceptorIndex = i;
	}
	return true;
}

//拦截器的后置处理方法调用,在真正的controller请求处理方法调用直接这里会执行
mappedHandler.applyPostHandle(processedRequest, response, mv);

void applyPostHandle(HttpServletRequest request, HttpServletResponse response, @Nullable ModelAndView mv)
			throws Exception {
	for (int i = this.interceptorList.size() - 1; i >= 0; i--) {
		HandlerInterceptor interceptor = this.interceptorList.get(i);
		//后置方法调用
		interceptor.postHandle(request, response, this.handler, mv);
	}
}

//处理完成之后的方法调用
processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException);

void triggerAfterCompletion(HttpServletRequest request, HttpServletResponse response, @Nullable Exception ex) {
	for (int i = this.interceptorIndex; i >= 0; i--) {
		HandlerInterceptor interceptor = this.interceptorList.get(i);
		try {
			//拦截器处理完成之后的方法调用
			interceptor.afterCompletion(request, response, this.handler, ex);
		}
		catch (Throwable ex2) {
			logger.error("HandlerInterceptor.afterCompletion threw exception", ex2);
		}
	}
}

3.1 拦截器示例

@Slf4j
@Component
public class HandlerInterceptorLearn implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new InterceptorLearn());
    }

    public class InterceptorLearn implements HandlerInterceptor {
        /**
         * 请求方法执行之前的处理
         *
         * @param request  请求体
         * @param response 返回结果
         * @param handler  处理方法
         * @return false 拒绝当前请求 true继续向后执行
         * @throws Exception 异常
         * @see org.springframework.web.servlet.DispatcherServlet#doDispatch(HttpServletRequest, HttpServletResponse)
         * - 1062行
         * if (!mappedHandler.applyPreHandle(processedRequest, response)) { //如果调用方法返回false转为ture直接返回 不进行方法调用 不进行后置处理等
         *  return;
         * }
         */
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            log.info("preHandle");
            return true;
        }

        @Override
        public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
            log.info("postHandler");
        }

        @Override
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
            log.info("afterCompletion");
        }
    }
}

4 真正controller方法调用分析

//ha局部变量 是前文中获取到的HandlerAdaptor适配器
mv = ha.handle(processedRequest, response, mappedHandler.getHandler());

//这里可以直接看到返回的参数类型是ModelAndView
public final ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
	return handleInternal(request, response, (HandlerMethod) handler);
}

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

	if (this.synchronizeOnSession) {
		//同步请求处理 - 不做分析 大致就是在session获取一个到一个预设置的对象并拿到他加锁并进行后续的处理
		HttpSession session = request.getSession(false);
		if (session != null) {
			Object mutex = WebUtils.getSessionMutex(session);
			synchronized (mutex) {
				mav = invokeHandlerMethod(request, response, handlerMethod);
			}
		}
		else {
			mav = invokeHandlerMethod(request, response, handlerMethod);
		}
	}
	else {
		//调用处理方法
		mav = invokeHandlerMethod(request, response, handlerMethod);
	}

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

4.1 跟着mav = invokeHandlerMethod(request,response,handlerMethod)方法继续分析

protected ModelAndView invokeHandlerMethod(HttpServletRequest request,
			HttpServletResponse response, HandlerMethod handlerMethod) throws Exception {
	ServletWebRequest webRequest = new ServletWebRequest(request, response);
	try {
		...
		//ServletInvocableHandlerMethod 继承了HandlerMethod
		ServletInvocableHandlerMethod invocableMethod = createInvocableHandlerMethod(handlerMethod);
		//分层处理(解耦),参数有参数解析器,返回值有返回值处理器
		if (this.argumentResolvers != null) {
			//设置参数解析器(将所有的参数解析器列表存入类成员中)
			invocableMethod.setHandlerMethodArgumentResolvers(this.argumentResolvers);
		}
		if (this.returnValueHandlers != null) {
			//设置方法返回值处理器
			invocableMethod.setHandlerMethodReturnValueHandlers(this.returnValueHandlers);
		}
		invocableMethod.setDataBinderFactory(binderFactory);
		invocableMethod.setParameterNameDiscoverer(this.parameterNameDiscoverer);

		ModelAndViewContainer mavContainer = new ModelAndViewContainer();
		...
		//在前置参数设置完毕之后调用处理方法
		invocableMethod.invokeAndHandle(webRequest, mavContainer);
		if (asyncManager.isConcurrentHandlingStarted()) {
			return null;
		}

		return getModelAndView(mavContainer, modelFactory, webRequest);
	}
	finally {
		webRequest.requestCompleted();
	}
}

4.3 invocableMethod.invokeAndHandle(webRequest, mavContainer)方法

public void invokeAndHandle(ServletWebRequest webRequest, ModelAndViewContainer mavContainer,
	Object... providedArgs) throws Exception {
	
	Object returnValue = invokeForRequest(webRequest, mavContainer, providedArgs);
	setResponseStatus(webRequest);
	
	if (returnValue == null) {
		if (isRequestNotModified(webRequest) || getResponseStatus() != null || mavContainer.isRequestHandled()) {
			disableContentCachingIfNecessary(webRequest);
			mavContainer.setRequestHandled(true);
			return;
		}
	}
	else if (StringUtils.hasText(getResponseStatusReason())) {
		mavContainer.setRequestHandled(true);
		return;
	}
	
	mavContainer.setRequestHandled(false);
	Assert.state(this.returnValueHandlers != null, "No return value handlers");
	try {
		this.returnValueHandlers.handleReturnValue(
				returnValue, getReturnValueType(returnValue), mavContainer, webRequest);
	}
	catch (Exception ex) {
		if (logger.isTraceEnabled()) {
			logger.trace(formatErrorForReturnValue(returnValue), ex);
		}
		throw ex;
	}
}

4.4 继续分析 Object returnValue = invokeForRequest(webRequest, mavContainer, providedArgs) 代码

public Object invokeForRequest(NativeWebRequest request, @Nullable ModelAndViewContainer mavContainer,
			Object... providedArgs) throws Exception {
	Object[] args = getMethodArgumentValues(request, mavContainer, providedArgs);
	if (logger.isTraceEnabled()) {
		logger.trace("Arguments: " + Arrays.toString(args));
	}
	return doInvoke(args);
}

protected Object doInvoke(Object... args) throws Exception {
	//获得执行方法
	Method method = getBridgedMethod();
	try {
		if (KotlinDetector.isSuspendingFunction(method)) {
			return CoroutinesUtils.invokeSuspendingFunction(method, getBean(), args);
		}
		//通过获取到的method进行回调并将参数带过去
		return method.invoke(getBean(), args);
	}
	catch (IllegalArgumentException ex) {
		assertTargetBean(method, getBean(), args);
		String text = (ex.getMessage() != null ? ex.getMessage() : "Illegal argument");
		throw new IllegalStateException(formatInvokeError(text, args), ex);
	}
	catch (InvocationTargetException ex) {
		// Unwrap for HandlerExceptionResolvers ...
		Throwable targetException = ex.getTargetException();
		if (targetException instanceof RuntimeException) {
			throw (RuntimeException) targetException;
		}
		else if (targetException instanceof Error) {
			throw (Error) targetException;
		}
		else if (targetException instanceof Exception) {
			throw (Exception) targetException;
		}
		else {
			throw new IllegalStateException(formatInvokeError("Invocation failure", args), targetException);
		}
	}
}

了结 太难写文档了以后有空再续写吧

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值