SpringMVC执行过程及HandlerAdapter分析

SpringMVC执行过程

20210705201138143
  1. 起初用户发送请求
  2. 前端控制器DispatchServlet接收用户请求,并委托给 处理器映射HandlerMapping
  3. HandlerMapping根据请求路径寻找到相应的处理执行链HandlerExecutionChain其中包含Handler以及拦截器Interpetor并返回给前端控制器
  4. DispatchServletHandler作为参数传递给合适的(根据Handler的实现方式-----基于(实现Controller, @Controller注解,实现HttpRequestHandler)HandlerAdapter,适配器调用handler方法处理核心业务逻辑并返回给前端控制器ModelAndView
  5. DiapatchServlet再次委托ViewResolver将页面解析,并渲染而后返回视图解析器
  6. 最终DisparchServlet相应了请求

AFQ:

为什么前端控制器不直接调用handler,而是在中间加一个适配器?

这是因为处理者的实现有多种(或许你平常我们只用过@Controller,Spring后期确实推荐使用这种方法)

实现Controller, @Controller注解,实现HttpRequestHandler
在这里插入图片描述

每一种方式都对应了一个适配器,

HandlerAdapter

public interface HandlerAdapter {
 
   boolean supports(Object handler);
    
   ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception;

   long getLastModified(HttpServletRequest request, Object handler);

}

supports ,根据传入的handler判断是否,该适配器是否支持

handler 是处理具体的请求

SimpleControllerHandlerAdapter 能处理基于实现Controller接口的处理器

HttpRequestHandlerAdapter 能处理基于实现HttpRequestHandler接口的处理器

HttpRequestHandlerAdapter 能处理基于**@Controller**实现的处理器

如果没有适配器,直接调用,大概就是这样的

if(handler instanceof 实现Controller接口){
	 handler.handle(request,response)
}else if(handler instanceof 实现HttpRequestHandler接口){
   	 handler.handle(request,response)
}else if(handler instanceof 基于@Controller){
      handler.handle(request,response)
}....

多层的if else 并不优雅,并且,以后如果由其他实现方式的处理器,我们不得不,修改这段代码,添加新的if lese,

违背了开闭原则,所以,Spring 并不这么做,添加了适配器这一层,从若干个适配器中寻找到一个合适的处理器。

--------------------从容器中获取所有适配器----------------------------
private void initHandlerAdapters(ApplicationContext context) {
   ...
    Map<String, HandlerAdapter> matchingBeans =
					BeanFactoryUtils.beansOfTypeIncludingAncestors(context, HandlerAdapter.class, true, false);
    ...
}
-----------------------寻找合适的适配器----------------------------------
protected HandlerAdapter getHandlerAdapter(Object handler) throws ServletException {
   if (this.handlerAdapters != null) {
      for (HandlerAdapter adapter : this.handlerAdapters) {
         if (adapter.supports(handler)) {
            return adapter;
         }
      }
   }
    ...
}

这样做之后,就避免了大量的if else,让我们的代码更优雅并且,如果将来新添加了其他处理器,我们只需要实现HandlerAdapter,

为它创建一个适配器,需要修改任何原来的代码,符合开闭原则

ps:这里虽然用到了适配器,但我感觉但不是适配器模式的思想(作为两个不兼容的接口之间的桥梁),而是Java多态的应用

所有的过程基本上都围绕着DispatchServlet,而其中的核心逻辑又在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 (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);
				}
			}
		}
	}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值