源码分析-请求处理

DispatcherServlet方法执行顺序

DispatcherServlet中引用类型的属性,是SpringMVC的九大组件,九大组件都在DispatcherServlet中初始化
SpringMVC工作的时候,关键位置都是由这些组件完成的

共同点:它们都是接口,接口就是规范

	/** MultipartResolver used by this servlet. */
	@Nullable
	private MultipartResolver multipartResolver;     //文件上传解析器

	/** LocaleResolver used by this servlet. */
	@Nullable
	private LocaleResolver localeResolver;        //区域信息解析器,和国际化有关

	/** ThemeResolver used by this servlet. */
	@Nullable
	private ThemeResolver themeResolver;  //主题解析器,强大的主题效果更换

	/** List of HandlerMappings used by this servlet. */
	@Nullable
	private List<HandlerMapping> handlerMappings;  //handler映射信息

	/** List of HandlerAdapters used by this servlet. */
	@Nullable
	private List<HandlerAdapter> handlerAdapters;  //handler适配器

	/** List of HandlerExceptionResolvers used by this servlet. */
	@Nullable
	private List<HandlerExceptionResolver> handlerExceptionResolvers;  //SpringMVC强大的异常解析功能:异常解析器

	/** RequestToViewNameTranslator used by this servlet. */
	@Nullable
	private RequestToViewNameTranslator viewNameTranslator;  //请求名作为视图名(没用)

	/** FlashMapManager used by this servlet. */  
	@Nullable
	private FlashMapManager flashMapManager;  //SpringMVC允许重定向携带数据的功能

	/** List of ViewResolvers used by this servlet. */
	@Nullable
	private List<ViewResolver> viewResolvers;  //视图解析器

  

 

  1. DispatcherServlet 拦截请求
  2. 调用doDispatch()方法进行处理
    1. getHandler():根据当前请求地址找到能处理这个请求的目标处理器类
    2. getHandlerAdapter():根据当前处理器类获取到能执行这个处理器方法的适配器
    3. 目标方法执行后会返回一个ModeAndView对象
    4. 根据ModelAndView的信息转发到具体的页面,并可以在请求域中取出ModelAndView中的数据
	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 {
				//1、检查是否文件上传请求
				processedRequest = checkMultipart(request);
				multipartRequestParsed = (processedRequest != request);

				//2、根据当前请求找到哪个类能进行处理,找到FirstController
				// Determine handler for the current request.
				mappedHandler = getHandler(processedRequest);
				//3、如果没有找到能处理请求的处理器,就404或者抛异常
				if (mappedHandler == null) {
					noHandlerFound(processedRequest, response);
					return;
				}
				//4、拿到能执行这个类里面所有方法的适配器(反射工具)RequestMappingHandlerAdapter
				// 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 (new ServletWebRequest(request, response).checkNotModified(lastModified) && isGet) {
						return;
					}
				}

				if (!mappedHandler.applyPreHandle(processedRequest, response)) {
					return;
				}
				//5、用适配器处理目标方法,将目标方法执行完成后的返回值作为视图名,保存到ModelAndView中,ModelAndView [view="success"; model={}]
				//请求处理,处理器的方法被调用
				// 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);
			}
			//根据封装的ModelAndView,转发到对应的页面,可以从请求域中获取ModelAndView的数据
			//转发到页面
			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);
				}
			}
		}
	}

  

 

getHandler()细节

返回值:HandlerExecutionChain with [com.tang.controller.FirstController#hello()] and 0 interceptors

HandlerMapping:处理器映射,里面保存了每一个处理器能处理哪些请求的映射信息

this.handlerMappings 是一个数组,对它进行遍历获得能处理请求的处理器

	protected HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
		if (this.handlerMappings != null) {
			for (HandlerMapping mapping : this.handlerMappings) {
				HandlerExecutionChain handler = mapping.getHandler(request);
				if (handler != null) {
					return handler;
				}
			}
		}
		return null;
	}

  

getHandlerAdapter()细节

HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());

mappedHandler.getHandler()执行结果:

com.tang.controller.FirstController#hello()

	protected HandlerAdapter getHandlerAdapter(Object handler) throws ServletException {
		if (this.handlerAdapters != null) {
			for (HandlerAdapter adapter : this.handlerAdapters) {
				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");
	}

 

this.handlerAdapters 是一个数组

 

 

 

 当执行到第三个执行的方法

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

 

posted @ 2021-04-14 11:23  455994206  阅读(62)  评论(0)    收藏  举报