聊聊Spring MVC中 handlerMapping和handlerAdapter设计思想

先上一段Spring MVC核心类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);

         // 根据当前请求获取对应的处理器映射器
         mappedHandler = getHandler(processedRequest);
         if (mappedHandler == null || mappedHandler.getHandler() == null) {
            noHandlerFound(processedRequest, response);
            return;
         }

         // 根据handler类型获取对应的处理器适配器
         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);
         }
      }
   }
}


关注代码中打中文注释的两个地方,一个获取对应handler的处理器映射器,一个获取对应handler的处理器适配器。那为什么需要这两个东西,我们直接在handler中写映射逻辑,直接通过handler来执行处理器方法难道不行吗?答案是否定的,但Spring为什么要这样做?有以下几个好处

1.将具体的handler与handlerMapping分离开,为了符合单一职责

2.让具体的处理器与DispatcherServlet解耦合,为了符合开闭原则
我们知道所有的处理器映射器都有共同的基类HandlerMapping,这个是可以确定的,也是不会改变的。而handler的类型在未来是极有可能变动或继续追加的。当前版本Spring有以下几种handler类型:
-HandlerMethod(通过RequestMappingHandlerMapping解析而来,我们最常使用的)
-Servlet(继承自Servlet接口的处理器)
-Controller(继承自Controller接口的处理器)
它们之前并没有共同的基类,也不可能有共同的基类,因为它们来自不同的包,来自不同的设计者。
Spring设计者将DispatcherServlet与HandlerMapping关联,当追加新的handler类型以后,现有代码并不需要改动,符合面向对象的又一原则:开闭原则。

处理器适配器与处理器映射器的作用类似,都是为了解耦合。

if(handler instanceof Servlet){
    (Servlet)handler.service();
}else if(handler instanceof HandlerMethod){
    (ServletInvocableHandlerMethod)handler.invokeAndHandle();
}else if (handler instanceof Controller){
    ((Controller) handler).handleRequest();
}

如果我们要新增一种处理器类型,必然要继续追写else if来进行处理,但使用处理器适配器后,DispatcherServlet不需要改动任何代码,因为它只依赖HandlerAdapter,这样DispatcherServlet与具体的Handler就解耦合了,它们之前可以独立发展。

优秀的程序员是艺术家,而艺术就是代码。

你可能感兴趣的:(springboot,spring-mvc,spring,java)