环境: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是我自定义的,大家可以忽略)
根据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发生异常后的处理逻辑。