環(huán)境:Springboot2.4.12
請(qǐng)求入口
SpringMVC的請(qǐng)求處理入口是DispatcherServlet,不過該Servlet不做實(shí)際的處理而實(shí)際的處理是由可其它配置的委托組件執(zhí)行的。
DispatcherServlet和任何Servlet一樣,需要使用JAVA配置或web.xml根據(jù)Servlet規(guī)范進(jìn)行聲明和映射。然后,DispatcherServlet使用Spring配置來發(fā)現(xiàn)它在請(qǐng)求映射、視圖解析、異常處理等方面所需的委托組件。如下配置示例:
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/*");
}
}
這里為何需要實(shí)現(xiàn)WebApplicationInitializer 這需要你先了解Servlet3.0+的新特性
ServletContainerInitializer
下面方法是DispatcherServlet處理的核心方法:
protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
try {
Exception dispatchException = null;
// 1.獲取HandlerMapping(該對(duì)象就是當(dāng)前請(qǐng)求與處理程序的一個(gè)映射關(guān)系)
mappedHandler = getHandler(processedRequest);
// 2.獲取能夠處理上一步得到的處理程序
HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());
// 3.執(zhí)行實(shí)際的調(diào)用(執(zhí)行實(shí)際的處理程序)
mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
} catch (Exception ex) {
// 4.執(zhí)行過程中發(fā)生異常記錄到局部變量中
dispatchException = ex;
} catch (Throwable err) {
dispatchException = new NestedServletException("Handler dispatch failed", err);
}
// 5.處理結(jié)果
processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException);
}
上面只是把核心的代碼貼出
處理結(jié)果
接著上一步中繼續(xù)執(zhí)行,這里就會(huì)根據(jù)上一步執(zhí)行過程中是否發(fā)生異常(異常對(duì)象是否為空)。
private void processDispatchResult(HttpServletRequest request, HttpServletResponse response,
@Nullable HandlerExecutionChain mappedHandler, @Nullable ModelAndView mv,
@Nullable Exception exception) throws Exception {
boolean errorView = false;
// 1.判斷是否發(fā)生異常
if (exception != null) {
// 1.1.異常對(duì)象是否是該對(duì)象
if (exception instanceof ModelAndViewDefiningException) {
mv = ((ModelAndViewDefiningException) exception).getModelAndView();
} else {
// 如果不是上面的異常對(duì)象,則這里獲取具體處理程序的Handler
// 這里我們只考慮RequestMappingHandlerMapping情況,那么這里獲取的將是HandlerMethod對(duì)象
// 也就是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);
}
}
重點(diǎn),處理異常
protected ModelAndView processHandlerException(HttpServletRequest request, HttpServletResponse response,
@Nullable Object handler, Exception ex) throws Exception {
ModelAndView exMv = null;
// 判斷當(dāng)前的異常解析器是否存在;也就是從容器中獲取所有HandlerExceptionResolver類型對(duì)象
// 這里我們就不展開了,你可以在DispatcherServlet中查看初始化過程
// 默認(rèn)情況下,這里集合中有如下圖1中所示
if (this.handlerExceptionResolvers != null) {
// 遍歷每一個(gè)異常處理器,誰能返回ModelAndView就結(jié)束循環(huán)
// 由于DefaultErrorAttributes內(nèi)部方法直接返回了null,所以這里返回的是HandlerExceptionResolverComposite
// 這是聚合類,聚合了其它3個(gè)具體的解析器,所以時(shí)間處理的還是其它類并非它
for (HandlerExceptionResolver resolver : this.handlerExceptionResolvers) {
// 結(jié)合上面說只考慮RequestMappingHandlerMapping處理Controller的情況
// 那這里合理的解析器是ExceptionHandlerExceptionResolver
exMv = resolver.resolveException(request, response, handler, ex);
if (exMv != null) {
break;
}
}
}
// 通過上面的執(zhí)行如果獲取到了ModelAndView對(duì)象,下面就是判斷視圖對(duì)象不同的情況如何進(jìn)行處理了
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是我自定義的,大家可以忽略)
默認(rèn)HandlerExceptionResolver集合
根據(jù)
ExceptionHandlerExceptionResolver 的繼承關(guān)系得到核心處理邏輯是如下方法:
protected ModelAndView doResolveHandlerMethodException(HttpServletRequest request,
HttpServletResponse response, @Nullable HandlerMethod handlerMethod, Exception exception) {
// 這里的整個(gè)過程會(huì)先從Controller中獲取所有@ExceptionHandler標(biāo)注的方法中獲取能夠
// 處理該異常的方法,如果沒有會(huì)從全局異常句柄中查找
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<>();
// 下面的流程就是執(zhí)行上面的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;
// 執(zhí)行方法調(diào)用(執(zhí)行@ExceptionHandler標(biāo)注的方法,這方法執(zhí)行過程中可能就直接向客戶端返回?cái)?shù)據(jù)了,比如基于Rest接口)
exceptionHandlerMethod.invokeAndHandle(webRequest, mavContainer, arguments);
} catch (Throwable invocationEx) {
// ...
return null;
}
if (mavContainer.isRequestHandled()) {
return new ModelAndView();
} else {
// 構(gòu)建ModelAndView對(duì)象
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發(fā)生異常后的處理邏輯。
完畢!!!