日日操夜夜添-日日操影院-日日草夜夜操-日日干干-精品一区二区三区波多野结衣-精品一区二区三区高清免费不卡

公告:魔扣目錄網為廣大站長提供免費收錄網站服務,提交前請做好本站友鏈:【 網站目錄:http://www.ylptlb.cn 】, 免友鏈快審服務(50元/站),

點擊這里在線咨詢客服
新站提交
  • 網站:51998
  • 待審:31
  • 小程序:12
  • 文章:1030137
  • 會員:747



環境:Springboot2.4.12

請求入口

SpringMVC的請求處理入口是DispatcherServlet,不過該Servlet不做實際的處理而實際的處理是由可其它配置的委托組件執行的。

DispatcherServlet和任何Servlet一樣,需要使用JAVA配置或web.xml根據Servlet規范進行聲明和映射。然后,DispatcherServlet使用Spring配置來發現它在請求映射、視圖解析、異常處理等方面所需的委托組件。如下配置示例:

public class CustomWebApplicationInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext servletContext) {
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.register(WebConfig.class);
        DispatcherServlet servlet = new DispatcherServlet(context);
        ServletRegistration.Dynamic registration = servletContext.addServlet("app", servlet);
        registration.setLoadOnStartup(1);
        registration.addMapping("/app/*");
    }
}

這里為何需要實現WebApplicationInitializer 這需要你先了解Servlet3.0+的新特性
ServletContainerInitializer

下面方法是DispatcherServlet處理的核心方法:

protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
  try {
    Exception dispatchException = null;
    // 1.獲取HandlerMapping(該對象就是當前請求與處理程序的一個映射關系)
    mappedHandler = getHandler(processedRequest);
    // 2.獲取能夠處理上一步得到的處理程序
    HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());
    // 3.執行實際的調用(執行實際的處理程序)
    mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
  } catch (Exception ex) {
    // 4.執行過程中發生異常記錄到局部變量中
    dispatchException = ex;
  } catch (Throwable err) {
    dispatchException = new NestedServletException("Handler dispatch failed", err);
  }
  // 5.處理結果
  processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException);
}

上面只是把核心的代碼貼出

處理結果

接著上一步中繼續執行,這里就會根據上一步執行過程中是否發生異常(異常對象是否為空)。

private void processDispatchResult(HttpServletRequest request, HttpServletResponse response,
			@Nullable HandlerExecutionChain mappedHandler, @Nullable ModelAndView mv,
			@Nullable Exception exception) throws Exception {

  boolean errorView = false;
  // 1.判斷是否發生異常
  if (exception != null) {
    // 1.1.異常對象是否是該對象
    if (exception instanceof ModelAndViewDefiningException) {
      mv = ((ModelAndViewDefiningException) exception).getModelAndView();
    } else {
      // 如果不是上面的異常對象,則這里獲取具體處理程序的Handler
      // 這里我們只考慮RequestMappingHandlerMapping情況,那么這里獲取的將是HandlerMethod對象
      // 也就是Controller中的具體方法了
      Object handler = (mappedHandler != null ? mappedHandler.getHandler() : null);
      // 處理異常,查看下面processhandlerException方法
      mv = processHandlerException(request, response, handler, exception);
      errorView = (mv != null);
    }
  }

  // Did the handler return a view to render?
  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;
  }

  if (mappedHandler != null) {
    // Exception (if any) is already handled..
    mappedHandler.triggerAfterCompletion(request, response, null);
  }
}

重點,處理異常

protected ModelAndView processHandlerException(HttpServletRequest request, HttpServletResponse response,
			@Nullable Object handler, Exception ex) throws Exception {
  ModelAndView exMv = null;
  // 判斷當前的異常解析器是否存在;也就是從容器中獲取所有HandlerExceptionResolver類型對象
  // 這里我們就不展開了,你可以在DispatcherServlet中查看初始化過程
  // 默認情況下,這里集合中有如下圖1中所示
  if (this.handlerExceptionResolvers != null) {
    // 遍歷每一個異常處理器,誰能返回ModelAndView就結束循環
    // 由于DefaultErrorAttributes內部方法直接返回了null,所以這里返回的是HandlerExceptionResolverComposite
    // 這是聚合類,聚合了其它3個具體的解析器,所以時間處理的還是其它類并非它
    for (HandlerExceptionResolver resolver : this.handlerExceptionResolvers) {
      // 結合上面說只考慮RequestMappingHandlerMapping處理Controller的情況
      // 那這里合理的解析器是ExceptionHandlerExceptionResolver
      exMv = resolver.resolveException(request, response, handler, ex);
      if (exMv != null) {
        break;
      }
    }
  }
  // 通過上面的執行如果獲取到了ModelAndView對象,下面就是判斷視圖對象不同的情況如何進行處理了
  if (exMv != null) {
    if (exMv.isEmpty()) {
      request.setAttribute(EXCEPTION_ATTRIBUTE, ex);
      return null;
    }
    if (!exMv.hasView()) {
      String defaultViewName = getDefaultViewName(request);
      if (defaultViewName != null) {
        exMv.setViewName(defaultViewName);
      }
    }
    WebUtils.exposeErrorRequestAttributes(request, ex, getServletName());
    // 如果存在要想前端展示的視圖,則返回。
    return exMv;
  }
  throw ex;
}

圖1(這里的CustomExceptionResolver是我自定義的,大家可以忽略)

默認HandlerExceptionResolver集合

根據
ExceptionHandlerExceptionResolver 的繼承關系得到核心處理邏輯是如下方法:

protected ModelAndView doResolveHandlerMethodException(HttpServletRequest request,
			HttpServletResponse response, @Nullable HandlerMethod handlerMethod, Exception exception) {
  // 這里的整個過程會先從Controller中獲取所有@ExceptionHandler標注的方法中獲取能夠
  // 處理該異常的方法,如果沒有會從全局異常句柄中查找
  ServletInvocableHandlerMethod exceptionHandlerMethod = getExceptionHandlerMethod(handlerMethod, exception);
  if (exceptionHandlerMethod == null) {
    return null;
  }
  // ...
  ServletWebRequest webRequest = new ServletWebRequest(request, response);
  ModelAndViewContainer mavContainer = new ModelAndViewContainer();
  ArrayList<Throwable> exceptions = new ArrayList<>();
  // 下面的流程就是執行上面的ServletInvocableHandlerMethod
  try {
    // Expose causes as provided arguments as well
    Throwable exToExpose = exception;
    while (exToExpose != null) {
      exceptions.add(exToExpose);
      Throwable cause = exToExpose.getCause();
      exToExpose = (cause != exToExpose ? cause : null);
    }
    Object[] arguments = new Object[exceptions.size() + 1];
    exceptions.toArray(arguments);  // efficient arraycopy call in ArrayList
    arguments[arguments.length - 1] = handlerMethod;
    // 執行方法調用(執行@ExceptionHandler標注的方法,這方法執行過程中可能就直接向客戶端返回數據了,比如基于Rest接口)
    exceptionHandlerMethod.invokeAndHandle(webRequest, mavContainer, arguments);
  } catch (Throwable invocationEx) {
    // ...
    return null;
  }

  if (mavContainer.isRequestHandled()) {
    return new ModelAndView();
  } else {
    // 構建ModelAndView對象
    ModelMap model = mavContainer.getModel();
    HttpStatus status = mavContainer.getStatus();
    ModelAndView mav = new ModelAndView(mavContainer.getViewName(), model, status);
    mav.setViewName(mavContainer.getViewName());
    if (!mavContainer.isViewReference()) {
      mav.setView((View) mavContainer.getView());
    }
    if (model instanceof RedirectAttributes) {
      Map<String, ?> flashAttributes = ((RedirectAttributes) model).getFlashAttributes();
      RequestContextUtils.getOutputFlashMap(request).putAll(flashAttributes);
    }
    return mav;
  }
}

上面大體上就是Controller發生異常后的處理邏輯。

完畢!!!

分享到:
標簽:SpringMVC
用戶無頭像

網友整理

注冊時間:

網站:5 個   小程序:0 個  文章:12 篇

  • 51998

    網站

  • 12

    小程序

  • 1030137

    文章

  • 747

    會員

趕快注冊賬號,推廣您的網站吧!
最新入駐小程序

數獨大挑戰2018-06-03

數獨一種數學游戲,玩家需要根據9

答題星2018-06-03

您可以通過答題星輕松地創建試卷

全階人生考試2018-06-03

各種考試題,題庫,初中,高中,大學四六

運動步數有氧達人2018-06-03

記錄運動步數,積累氧氣值。還可偷

每日養生app2018-06-03

每日養生,天天健康

體育訓練成績評定2018-06-03

通用課目體育訓練成績評定