SpringMvc的運行流程你真的懂了嗎?

MVC思想

​ 模型-視圖-控制器(MVC)是一個衆所周知的以設計界面應用程序爲基礎的設計思想。它主要經過分離模型、視圖及控制器在應用程序中的角色將業務邏輯從界面中解耦。一般,模型負責封裝應用程序數據在視圖層展現。視圖僅僅只是展現這些數據,不包含任何業務邏輯。控制器負責接收來自用戶的請求,並調用後臺服務(service或者dao)來處理業務邏輯。處理後,後臺業務層可能會返回了一些數據在視圖層展現。控制器收集這些數據及準備模型在視圖層展現。MVC模式的核心思想是將業務邏輯從界面中分離出來,容許它們單獨改變而不會相互影響。前端

UkrLLR.png

SpringMvc 請求流程

Ukrqy9.png

Spring MVC框架也是一個基於請求驅動的Web框架,而且使用了前端控制器模式(是用來提供一個集中的請求處理機制,全部的請求都將由一個單一的處理程序處理來進行設計,再根據請求映射規則分發給相應的頁面控制器(動做/處理器)進行處理。首先讓咱們總體看一下Spring MVC處理請求的流程:java

  1. 首先用戶發送請求,請求被SpringMvc前端控制器(DispatherServlet)捕獲;
  2. 前端控制器(DispatherServlet)對請求URL解析獲取請求URI,根據URI, 調用HandlerMapping;
  3. 前端控制器(DispatherServlet)得到返回的HandlerExecutionChain(包括Handler對象以及Handler對象對應的攔截器);
  4. DispatcherServlet 根據得到的HandlerExecutionChain,選擇一個合適的HandlerAdapter。(附註:若是成功得到HandlerAdapter後,此時將開始執行攔截器的preHandler(...)方法);
  5. HandlerAdapter根據請求的Handler適配並執行對應的Handler;HandlerAdapter(提取Request中的模型數據,填充Handler入參,開始執行Handler(Controller)。 在填充Handler的入參過程當中,根據配置,Spring將作一些額外的工做:

    HttpMessageConveter: 將請求消息(如Json、xml等數據)轉換成一個對象,將對象轉換爲指定的響應信息。node

    數據轉換:對請求消息進行數據轉換。如String轉換成Integer、Double等數據格式化:ios

    數據格式化。 如將字符串轉換成格式化數字或格式化日期等web

    數據驗證: 驗證數據的有效性(長度、格式等),驗證結果存儲到BindingResult或Error中)spring

  6. Handler執行完畢,返回一個ModelAndView(即模型和視圖)給HandlerAdaptor
  7. HandlerAdaptor適配器將執行結果ModelAndView返回給前端控制器。
  8. 前端控制器接收到ModelAndView後,請求對應的視圖解析器。
  9. 視圖解析器解析ModelAndView後返回對應View;
  10. 渲染視圖並返回渲染後的視圖給前端控制器。

十一、最終前端控制器將渲染後的頁面響應給用戶或客戶端緩存

SpringMvc 請求執行源碼解讀

​ 對於SpringMvc 項目全部的請求入口(靜態資源除外)這裏都是從web.xml文件配置的前端控制器DispatcherServlet開始,mvc

<!-- servlet請求分發器 -->
<servlet>
  <servlet-name>springMvc</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <init-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:servlet-context.xml</param-value>
  </init-param>
  <!-- 表示啓動容器時初始化該Servlet -->
  <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
  <servlet-name>springMvc</servlet-name>
  <!-- 這是攔截請求, /表明攔截全部請求,攔截全部.do請求 -->
  <url-pattern>/</url-pattern>
</servlet-mapping>

DispatcherServlet UML繼承關係圖以下:app

UkroJU.png

這裏關注藍線部分繼承結構:DispatcherServlet-->FrameworkServlet-->HttpServletBean-->HttpServlet-->GenericServlet-->Servlet,對於請求核心時序圖以下:框架

UkrTWF.jpg

對於web 請求的處理,你們都知道是經過繼承HttpServlet重寫其service方法,這裏打開DispatcherServlet源碼發現這裏並無看到咱們要找的service方法,此時到父類FrameworkServlet 查找以下:能夠看到父類重寫HttpServlet service方法。

FrameworkServlet #service

/**
 * Override the parent class implementation in order to intercept PATCH requests.
 */
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
   HttpMethod httpMethod = HttpMethod.resolve(request.getMethod());
   if (httpMethod == HttpMethod.PATCH || httpMethod == null) {
      processRequest(request, response);
   }
   else {
      super.service(request, response);
   }
}

​ 從源碼分析來看當請求方法爲patch請求或者爲null時執行processRequest 方法,其餘狀況則調用父類service 方法,你們都知道SpringMvc 請求大多請求是get|post請求爲主,此時繼續向上查看FrameworkServlet 父類HttpServletBean(抽象類繼承HttpServlet 並未重寫service方法 因此向上繼續尋找)-->HttpServlet service 方法

HttpServlet#service

@Override
    public void service(ServletRequest req, ServletResponse res)
        throws ServletException, IOException
    {
        HttpServletRequest  request;
        HttpServletResponse response;
        
        if (!(req instanceof HttpServletRequest &&
                res instanceof HttpServletResponse)) {
            throw new ServletException("non-HTTP request or response");
        }

        request = (HttpServletRequest) req;
        response = (HttpServletResponse) res;

        service(request, response);
    }
}


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) {
                // servlet doesn't support if-modified-since, no reason
                // to go through further expensive logic
                doGet(req, resp);
            } else {
                long ifModifiedSince = req.getDateHeader(HEADER_IFMODSINCE);
                if (ifModifiedSince < lastModified) {
                    // If the servlet mod time is later, call doGet()
                    // Round down to the nearest second for a proper compare
                    // A ifModifiedSince of -1 will always be less
                    maybeSetLastModified(resp, lastModified);
                    doGet(req, resp);
                } else {
                    resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                }
            }

        } else if (method.equals(METHOD_HEAD)) {
            long lastModified = getLastModified(req);
            maybeSetLastModified(resp, lastModified);
            doHead(req, resp);

        } else if (method.equals(METHOD_POST)) {
            doPost(req, resp);
            
        } else if (method.equals(METHOD_PUT)) {
            doPut(req, resp);
            
        } else if (method.equals(METHOD_DELETE)) {
            doDelete(req, resp);
            
        } else if (method.equals(METHOD_OPTIONS)) {
            doOptions(req,resp);
            
        } else if (method.equals(METHOD_TRACE)) {
            doTrace(req,resp);
            
        } else {
            //
            // Note that this means NO servlet supports whatever
            // method was requested, anywhere on this server.
            //

            String errMsg = lStrings.getString("http.method_not_implemented");
            Object[] errArgs = new Object[1];
            errArgs[0] = method;
            errMsg = MessageFormat.format(errMsg, errArgs);
            
            resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, errMsg);
        }
    }

能夠看到HttpServlet service 進行了重載,根據不一樣的請求類型而後調用不一樣處理方法,這裏以get請求爲例,當請求方法爲get 請求時在重載service 方法中調用doGet 方法進行處理,這裏須要特別注意的是:HttpServlet 存在doGet方法實現,然而在繼承的子類中也存在doGet方法實現,到底調用哪一個方法?很明顯調用子類的doGet方法(面向對象多態思想!!!),從繼承UML關係圖上看,最外層子類實現doGet方法的爲FrameworkServlet

FrameworkServlet #doGet&processRequest

@Override
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 {

        // 系統計時開始時間
        long startTime = System.currentTimeMillis();
        Throwable failureCause = null;
        // 國際化
        LocaleContext previousLocaleContext = LocaleContextHolder.getLocaleContext();
        LocaleContext localeContext = buildLocaleContext(request);
        //構建ServletRequestAttributes對象
        RequestAttributes previousAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes requestAttributes = buildRequestAttributes(request, response, previousAttributes);
        //異步管理
        WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
        asyncManager.registerCallableInterceptor(FrameworkServlet.class.getName(), new RequestBindingInterceptor());
        //初始化ContextHolders
        initContextHolders(request, localeContext, requestAttributes);

        try {
            doService(request, response);
        }
        catch (ServletException | IOException ex) {
            failureCause = ex;
            throw ex;
        }
        catch (Throwable ex) {
            failureCause = ex;
            throw new NestedServletException("Request processing failed", ex);
        }

        finally {
             //恢復原來的LocaleContext和ServiceRequestAttributes到LocaleContextHolder和RequestContextHolder,避免影響Servlet之外的處理,如Filter
            resetContextHolders(request, previousLocaleContext, previousAttributes);
            if (requestAttributes != null) {
                requestAttributes.requestCompleted();
            }
            logResult(request, response, failureCause, asyncManager);
            //發佈ServletRequestHandlerEvent消息,這個請求是否執行成功都會發布消息的
            publishRequestHandledEvent(request, response, startTime, failureCause);
        }
    }




// initContextHolders(request, localeContext, requestAttributes);
    private void initContextHolders(HttpServletRequest request,
            @Nullable LocaleContext localeContext, @Nullable RequestAttributes requestAttributes) {

        if (localeContext != null) {
            LocaleContextHolder.setLocaleContext(localeContext, this.threadContextInheritable);
        }
        if (requestAttributes != null) {
            RequestContextHolder.setRequestAttributes(requestAttributes, this.threadContextInheritable);
        }
    }

​ 該方法大概作了這幾件事:國際化的設置,建立ServletRequestAttributes對象,初始化上下文holders(即將Request對象放入到線程上下文中,如後續想要在方法中獲取request,response對象此時能夠經過調用LocaleContextHolder對應方法便可),而後調用doService方法。對於doService方法,FrameworkServlet 類並未提供實現,該方法由DispatcherServlet子類實現

DispatcherServlet#doService

DispatcherServlet裏面執行處理的入口方法是doService,因爲這個類繼承於FrameworkServlet類,重寫了doService()方法

@Override
protected void doService(HttpServletRequest request, HttpServletResponse response) throws Exception {
   logRequest(request);

   // Keep a snapshot of the request attributes in case of an include,
   // to be able to restore the original attributes after the include.
   Map<String, Object> attributesSnapshot = null;
   if (WebUtils.isIncludeRequest(request)) {
      attributesSnapshot = new HashMap<>();
      Enumeration<?> attrNames = request.getAttributeNames();
      while (attrNames.hasMoreElements()) {
         String attrName = (String) attrNames.nextElement();
         if (this.cleanupAfterInclude || attrName.startsWith(DEFAULT_STRATEGIES_PREFIX)) {
            attributesSnapshot.put(attrName, request.getAttribute(attrName));
         }
      }
   }

    //Spring上下文
   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);
   }

   try {
      //request設置完相關的屬性作真正的請求處理
      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);
         }
      }
   }
}

​ 整個方法看下來處理的操做有:處理include標籤的請求,將上下文放到request的屬性中,將國際化解析器放到request的屬性中,將主題解析器放到request屬性中,將主題放到request的屬性中,處理重定向的請求數據最後調用doDispatch這個核心的方法對請求進行處理。

DispatcherServlet#doDispatch

該方法是在doService方法中調用的,從底層設計了整個請求的處理流程:

  • 根據request找到Handler
  • 根據Handler找到對應的HandlerAdapter
  • 用HandlerAdapter處理Handler
  • 調用 processDispatchResult方法處理上面以後的結果(包含View渲染並輸出給用戶)
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 {
          // 校驗是否爲上傳請求 是上傳請求執行解析 不然返回request
         processedRequest = checkMultipart(request);
         multipartRequestParsed = (processedRequest != request);

         // 根據訪問的Handler 返回指定對應的HandlerExecutionChain對象 這裏從HandlerMapping 集合中查找 HandlerExecutionChain 對象包含Handler與攔截器HandlerInterceptor列表
         mappedHandler = getHandler(processedRequest);
         if (mappedHandler == null) {
            noHandlerFound(processedRequest, response);
            return;
         }

         // 根據獲得的Handler 獲取對應的HandlerAdaptor對象
         HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());

         // 處理GET、HEAD請求的Last-Modified
         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;
            }
         }

         //執行Interceptor的preHandle 
         if (!mappedHandler.applyPreHandle(processedRequest, response)) {
            return;
         }

         // 執行Handler 返回ModelAndView
         mv = ha.handle(processedRequest, response, mappedHandler.getHandler());

          //若是須要異步處理,直接返回
         if (asyncManager.isConcurrentHandlingStarted()) {
            return;
         }

         //當view爲空時,根據request設置默認view,如Handler返回值爲void
         applyDefaultViewName(processedRequest, mv);
         //執行相應Interceptor的postHandle 
         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);
      }
       //處理返回結果,包括處理異常、渲染頁面,發出完成通知觸發Interceptor的afterCompletion
      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);
         }
      }
   }
}
1. doDispatcher首先檢查是否是上傳請求,若是是則將request轉換爲MultipartHttpServletRequest,並將multipartRequestParsed標誌設置爲true
  1. 經過getHandler獲取Handler處理器鏈HandlerExecutionChain
    ​ 3. 處理GET、HEAD請求的Last-Modified,這裏主要判斷Last-Modified值是否被修改來處理決定是否採用緩存數據。
    ​ 4. 接下來依次調用相應的Interceptor的preHandle。執行攔截器攔截操做
    ​ 5. 攔截器preHandle方法執行後,此時開始經過HandlerAdapter 適配對應的Handler 執行(這裏纔是真正要執行的Controller方法), Handler處理完請求後,若是須要異步處理則直接返回,若是不須要異步處理,當view爲空時,設置默認view,而後執行相應的Interceptor的postHandle。
  • [ ] Handler:處理器,他直接對應着MVC中的C,也就是Controller層,它的具體表現形式有不少,能夠是類,也能夠是方法(一般以方法居多),由於它的定義是Object,咱們在方法中標註的@RequestMapping的全部方法均可以當作一個Handler,只要能夠實際處理請求的均可以當作Handler
  • [ ] HandlerMapping:用來查找Handler,在SpringMVC中會處理不少請求,每個請求都須要一個Handler來處理,具體接受到請求後須要哪個Handler來處理,此時經過HandlerMapping來實現查找。
  • [ ] HandlerAdapter:適配器,不一樣的Handler須要找到不一樣HandlerAdapter來調用Handler。就如工廠裏須要使用工具,工人(HandlerAdapter)使用工具(Handler)完成工做,而HandlerMapping用於根據須要完成的工做來找到相應的工具。

DispatcherServlet#processDispatchResult

processDispatchResult方法主要用來處理前面返回的結果,其中包括處理異常、渲染頁面、觸發Interceptor的afterCompletion方法三部份內容,處理的異常是在處理請求doDispatch方的過程當中產生。
private void processDispatchResult(HttpServletRequest request, HttpServletResponse response,
      @Nullable HandlerExecutionChain mappedHandler, @Nullable ModelAndView mv,
      @Nullable Exception exception) throws Exception {

   boolean errorView = false;
   // 若是請求過程當中有異常拋出則處理異常
   if (exception != null) {
      if (exception instanceof ModelAndViewDefiningException) {
         logger.debug("ModelAndViewDefiningException encountered", exception);
         mv = ((ModelAndViewDefiningException) exception).getModelAndView();
      }
      else {
         Object handler = (mappedHandler != null ? mappedHandler.getHandler() : null);
         mv = processHandlerException(request, response, handler, exception);
         errorView = (mv != null);
      }
   }

   //執行頁面渲染操做
   if (mv != null && !mv.wasCleared()) {
      render(mv, request, response);
      if (errorView) {
         WebUtils.clearErrorRequestAttributes(request);
      }
   }
   else {
      if (logger.isTraceEnabled()) {
         logger.trace("No view rendering, null ModelAndView returned.");
      }
   }

   if (WebAsyncUtils.getAsyncManager(request).isConcurrentHandlingStarted()) {
      // Concurrent handling started during a forward
      return;
   }

   // Handler請求處理完,觸發Interceptor的afterCompletion
   if (mappedHandler != null) {
      // Exception (if any) is already handled..
      mappedHandler.triggerAfterCompletion(request, response, null);
   }
}

render 視圖渲染

protected void render(ModelAndView mv, HttpServletRequest request, HttpServletResponse response) throws Exception {
   // Determine locale for request and apply it to the response.
   Locale locale =
         (this.localeResolver != null ? this.localeResolver.resolveLocale(request) : request.getLocale());
   response.setLocale(locale);

   View view;
   String viewName = mv.getViewName();
   if (viewName != null) {
      // We need to resolve the view name.
      view = resolveViewName(viewName, mv.getModelInternal(), locale, request);
      if (view == null) {
         throw new ServletException("Could not resolve view with name '" + mv.getViewName() +
               "' in servlet with name '" + getServletName() + "'");
      }
   }
   else {
      // No need to lookup: the ModelAndView object contains the actual View object.
      view = mv.getView();
      if (view == null) {
         throw new ServletException("ModelAndView [" + mv + "] neither contains a view name nor a " +
               "View object in servlet with name '" + getServletName() + "'");
      }
   }

 
   if (logger.isTraceEnabled()) {
      logger.trace("Rendering view [" + view + "] ");
   }
   try {
      if (mv.getStatus() != null) {
         response.setStatus(mv.getStatus().value());
      }
       // 渲染頁面處理
      view.render(mv.getModelInternal(), request, response);
   }
   catch (Exception ex) {
      if (logger.isDebugEnabled()) {
         logger.debug("Error rendering view [" + view + "]", ex);
      }
      throw ex;
   }
}

手寫SpringMVC

Spring MVC 的實現流程:

客戶端請求被 DispatcherServlet(前端控制器)接收。
->根據 HandlerMapping 映射到 Handler。
->生成 Handler 和 HandlerInterceptor(若是有則生成)。
->Handler 和 HandlerInterceptor 以 HandlerExecutionChain 的形式一併返回給 DispatcherServlet。
->DispatcherServlet 經過 HandlerAdapter 調用 Handler 的方法作業務邏輯處理。
->返回一個 ModelAndView 對象給 DispatcherServlet。
->DispatcherServlet 將獲取的 ModelAndView 對象傳給 ViewResolver 視圖解析器,將邏輯視圖解析成物理視圖 View。
->ViewResolver 返回一個 View 給 DispatcherServlet。
->DispatcherServlet 根據 View 進行視圖渲染(將模型數據填充到視圖中)。
->DispatcherServlet 將渲染後的視圖響應給客戶端。

分析

HTTP 請求是經過註解找到對應的 Controller 對象…;
Controller 的 Method 也是經過註解與 HTTP 請求映射的;
使用map 當作 ioC 容器,完成儲存全部參數與業務的class;

業務邏輯

初始化工做完成,接下來處理 HTTP 請求,業務流程以下:
DispatcherServlet 接收請求,經過映射從 IoC 容器中獲取對應的 Controller 對象;
根據映射獲取 Controller 對象對應的 Method;
調用 Method,獲取返回值;
將返回值傳給視圖解析器,返回物理視圖;
完成頁面跳轉。

自定義註解

@MyController
@MyRequestMapping

/**
 *   自定義  @RequestMapping  註解
 */
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyRequestMapping {
    String value() default "";
}

/**
 * @auther SyntacticSugar
 * @data 2018/11/13 0013下午 9:15
 */
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyController {
    String value() default "";
}

定義一個核心控制器MyDispatcherServlet

/**
 * @auther SyntacticSugar
 * @data 2018/11/13 0013下午 9:20
 * <p>
 * 建立控制器
 */
public class MyDispatcherServlet extends HttpServlet {
    //建立ioC  建立 handler存放容器

    private HashMap<String, Object> ioC = new HashMap<>();
    private HashMap<String, Method> handlerMapping = new HashMap<>();
    //自定義視圖解析
    private MyViewResolver myViewResolver;

    @Override
    public void init(ServletConfig config) throws ServletException {
        // 把controller放到ioC中
        scanController(config);
        //初始化handler 映射
        initHandlerMapping();
        //加載視圖解析器
        loadViewResolver(config);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String handlerUri = req.getRequestURI().split("/")[2];
        String methodUri = req.getRequestURI().split("/")[3];
        //
        Object o = ioC.get(handlerUri);
        Method method = handlerMapping.get(methodUri);
        //  使用反射機制,調用執行 業務
        try {
            String value = (String) method.invoke(o);
            //  將邏輯視圖  轉化爲   物理視圖,交給  view渲染返回前端
            String result  = myViewResolver.jspMapping(value);
            req.getRequestDispatcher(result).forward(req,resp );

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
  /**
     * saxReader 解析springmvc.xml
     * @param config
     */
    private void scanController(ServletConfig config) {
        SAXReader saxReader = new SAXReader();
        try {
            String path = config.getServletContext().getRealPath("") + "\\WEB-INF\\classes\\" +
                    config.getInitParameter("contextConfigLocation");
            Document document = saxReader.read(path);
            // 獲取根元素
            Element rootElement = document.getRootElement();
            Iterator iterator = rootElement.elementIterator();
            // 遍歷 nodes  、sax解析每一行xml
            while (iterator.hasNext()) {
                Element next = (Element) iterator.next();
                // 把每個元素的name和 component-scan  比較,獲取base-package值
                if (next.getName().equals("component-scan")) {
                    String packageName = next.attributeValue("base-package");
                    // 獲取包下 每一個子包
                    List<String> classNames = getClassNames(packageName);
                    for (String className : classNames) {
                        /**
                        經過反射獲取clazz  ,判斷class上是否存在MyController註解
                         *   若存在 、獲取MyRequestMapping 的 value , 並將其 裝入 自定義的ioC
                          */
                        Class<?> clazz = Class.forName(className);
                        if (clazz.isAnnotationPresent(MyController.class)) {
                            MyRequestMapping annotation  = clazz.getAnnotation(MyRequestMapping.class);
                            String value = annotation.value().substring(1);
                            // 放入ioC
                            ioC.put(value,clazz.newInstance() );
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 獲取 <context:component-scan base-package="com.baidu"/> 全部class 全路徑名
     * @param packageName
     * @return
     */
    private List<String> getClassNames(String packageName) {
        List<String> classNameList = new ArrayList<String>();
        String path = packageName.replace(".", "/");
        //已知存在包路徑,獲取每一級路徑下的file、 獲取類加載器,
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        URL url = classLoader.getResource(path);
        //非空判斷
        if (url != null) {
            File[] files = new File(url.getPath()).listFiles();
            //遍歷取值
            for (File childFile : files) {
                String className = packageName + "." + childFile.getName().replace(".class", "");
                classNameList.add(className);
            }
        }
        // return
        return classNameList;
    }

    /**
     * 初始化 handler
     */
    private void initHandlerMapping() {
                //從ioC中取出 MyController註解的 class
        for (String s : ioC.keySet()) {
            Class<?> clazz = ioC.get(s).getClass();
            Method[] methods = clazz.getMethods();
            //遍歷
            for (Method method : methods) {
                // 判斷哪個被 @MyRequestMapping 註解標識
                if (method.isAnnotationPresent(MyRequestMapping.class)) {
                    MyRequestMapping annotation = method.getAnnotation(MyRequestMapping.class);
                    String value = annotation.value().substring(1);
                    //   存入 handler
                    handlerMapping.put(value,method );
                }
            }
        }
    }

    /**
     *   加載自定義視圖  saxReader 解析springmvc.xml
     * @param config
     */
    private void loadViewResolver(ServletConfig config) {
        SAXReader reader = new SAXReader();
        try {
            String path = config.getServletContext().getRealPath("")+"\\WEB-INF\\classes\\"+config.getInitParameter("contextConfigLocation");
            Document document = reader.read(path);
            Element root = document.getRootElement();
            Iterator iter = root.elementIterator();
            //遍歷
            while(iter.hasNext()){
                Element ele = (Element) iter.next();
                if(ele.getName().equals("bean")){
                    String className = ele.attributeValue("class");
                    Class clazz = Class.forName(className);
                    Object obj = clazz.newInstance();
                    //獲取 setter 方法
                    Method prefixMethod = clazz.getMethod("setPrefix", String.class);
                    Method suffixMethod = clazz.getMethod("setSuffix", String.class);
                    Iterator beanIter = ele.elementIterator();
                    //獲取 property 值
                    Map<String,String> propertyMap = new HashMap<String,String>();
                    while(beanIter.hasNext()){
                        Element beanEle = (Element) beanIter.next();
                        String name = beanEle.attributeValue("name");
                        String value = beanEle.attributeValue("value");
                        propertyMap.put(name, value);
                    }
                    for(String str:propertyMap.keySet()){
                        //反射機制調用 setter 方法,完成賦值
                        if(str.equals("prefix")){
                            prefixMethod.invoke(obj, propertyMap.get(str));
                        }
                        if(str.equals("suffix")){
                            suffixMethod.invoke(obj, propertyMap.get(str));
                        }
                    }
                    myViewResolver = (MyViewResolver) obj;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

自定義一個視圖解析器,MyViewResolver

/**
 * @auther SyntacticSugar
 * @data 2018/11/13 0013下午 9:31
 *
 * 自定義視圖解析器 MyViewResolver
 */
public class MyViewResolver {
    private  String prefix;
    private  String suffix;
    //  目標資源路徑
    public String jspMapping(String value){
        return this.prefix+value+this.suffix;
    }
    //setter  getter
    ......
}

建立測試 TestController ,對自定義的springmvc 進行測試

/**
 * @auther SyntacticSugar
 * @data 2018/11/13 0013下午 10:47
 */
@MyController
@MyRequestMapping("/testController")
public class TestController {
    @MyRequestMapping("/test")
    public  String test(){
        System.out.println("執行test相關業務");
        return "index";
    }
}

springmvc.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<beans>
    <component-scan base-package="com.baidu"/>
    <!-- 配置視圖解析器 ,攔截器 -->
    <bean class="com.baidu.view.MyViewResolver">
        <property name="prefix" value="/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>
若是須要更多資料:1080355292(進羣暗號:99)

image

相關文章
相關標籤/搜索