Spring 中整个处理请求的主流程是啥?经常进行 spring 开发,大家知道拦截器,过滤器,还有具体的 Controller 处理。大体的顺序也能理清楚。但是不看源码总觉得不踏实。那么 spring 到底是如何处理的呢?事实上,非常简单。用不了 5 分钟,你就达到给别人讲解程度。
public class DispatcherServlet extends FrameworkServlet {
private List<HandlerAdapter> handlerAdapters;
private List<HandlerMapping> handlerMappings;
private void initHandlerAdapters(ApplicationContext context) {
this.handlerAdapters = null;
if (this.detectAllHandlerAdapters) {
// 从 context 查
Map<String, HandlerAdapter> matchingBeans =
BeanFactoryUtils.beansOfTypeIncludingAncestors(context, HandlerAdapter.class, true, false);
if (!matchingBeans.isEmpty()) {
this.handlerAdapters = new ArrayList<>(matchingBeans.values());
// We keep HandlerAdapters in sorted order.
AnnotationAwareOrderComparator.sort(this.handlerAdapters);
}
}
else {
try {
// 从 context 配置中找
HandlerAdapter ha = context.getBean(HANDLER_ADAPTER_BEAN_NAME, HandlerAdapter.class);
this.handlerAdapters = Collections.singletonList(ha);
}
catch (NoSuchBeanDefinitionException ex) {
// Ignore, we'll add a default HandlerAdapter later.
}
}
// 默认的
if (this.handlerAdapters == null) {
this.handlerAdapters = getDefaultStrategies(context, HandlerAdapter.class);
}
}
private void initHandlerMappings(ApplicationContext context) {
this.handlerMappings = null;
if (this.detectAllHandlerMappings) {
// 从 context 查
Map<String, HandlerMapping> matchingBeans =
BeanFactoryUtils.beansOfTypeIncludingAncestors(context, HandlerMapping.class, true, false);
if (!matchingBeans.isEmpty()) {
this.handlerMappings = new ArrayList<>(matchingBeans.values());
// We keep HandlerMappings in sorted order.
AnnotationAwareOrderComparator.sort(this.handlerMappings);
}
}
else {
try {
// 从 context 配置中找
HandlerMapping hm = context.getBean(HANDLER_MAPPING_BEAN_NAME, HandlerMapping.class);
this.handlerMappings = Collections.singletonList(hm);
}
catch (NoSuchBeanDefinitionException ex) {
// Ignore, we'll add a default HandlerMapping later.
}
}
// 默认的
if (this.handlerMappings == null) {
this.handlerMappings = getDefaultStrategies(context, HandlerMapping.class);
}
}
@Override
protected void doService(HttpServletRequest request, HttpServletResponse response) throws Exception {
// Make framework objects available to handlers and view objects.
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());
doDispatch(request, response);
}
protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
HttpServletRequest processedRequest = request;
try {
// 从 handlerMappings 找到 processedRequest 对应的 HandlerExecutionChain
HandlerExecutionChain mappedHandler = getHandler(processedRequest);
// 调用 mappedHandler 中每个拦截器的 PreHandler 方法。如果某个拦截器返回 false,请求处理就此完成。
if (!mappedHandler.applyPreHandle(processedRequest, response)) {
return;
}
// 从 handlerAdapters 根据 mappedHandler 找到对应的 HandlerAdapter
HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());
// 调用 HandlerAdapter 的 handler 方法处理请求
mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
// 生成 ModelAndView
applyDefaultViewName(processedRequest, mv);
ModelAndView mv = null;
// 调用 mappedHandler 中每个拦截器的 PostHandler 方法。
mappedHandler.applyPostHandle(processedRequest, response, mv);
} catch (Exception var20) {
} catch (Throwable var21) {
}
// 调用 mappedHandler 中每个拦截器的 triggerAfterCompletion 方法。
processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException);
}
protected HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
if (this.handlerMappings != null) {
for (HandlerMapping mapping : this.handlerMappings) {
HandlerExecutionChain handler = mapping.getHandler(request);
if (handler != null) {
return handler;
}
}
}
return null;
}
protected HandlerAdapter getHandlerAdapter(Object handler) throws ServletException {
if (this.handlerAdapters != null) {
for (HandlerAdapter adapter : this.handlerAdapters) {
if (adapter.supports(handler)) {
return adapter;
}
}
}
throw new ServletException("No adapter for handler [" + handler +
"]: The DispatcherServlet configuration needs to include a HandlerAdapter that supports this handler");
}
private void processDispatchResult(HttpServletRequest request, HttpServletResponse response,
@Nullable HandlerExecutionChain mappedHandler, @Nullable ModelAndView mv,
@Nullable Exception exception) throws Exception {
// 生成 ModelAndView
if (mv != null && !mv.wasCleared()) {
render(mv, request, response);
}
if (mappedHandler != null) {
mappedHandler.triggerAfterCompletion(request, response, null);
}
}
protected void render(ModelAndView mv, HttpServletRequest request, HttpServletResponse response) throws Exception {
View view;
String viewName = mv.getViewName();
if (viewName != null) {
// 优先使用 viewName
view = resolveViewName(viewName, mv.getModelInternal(), locale, request);
}
else {
// 其次 View
view = mv.getView();
}
if (mv.getStatus() != null) {
response.setStatus(mv.getStatus().value());
}
view.render(mv.getModelInternal(), request, response);
}
}
处理器相关
public class HandlerExecutionChain {
private final Object handler;
@Nullable
private HandlerInterceptor[] interceptors;
@Nullable
private List<HandlerInterceptor> interceptorList;
private int interceptorIndex = -1;
// 调用每个拦截器的 PreHandler 方法:
// 1. 如果返回 true,继续下一个拦截器。
// 2. 如果返回 false,调用已调用 preHandler 方法的拦截器的 afterCompletion,请求处理就此完成。
boolean applyPreHandle(HttpServletRequest request, HttpServletResponse response) throws Exception {
HandlerInterceptor[] interceptors = getInterceptors();
if (!ObjectUtils.isEmpty(interceptors)) {
for (int i = 0; i < interceptors.length; i++) {
HandlerInterceptor interceptor = interceptors[i];
if (!interceptor.preHandle(request, response, this.handler)) {
triggerAfterCompletion(request, response, null);
return false;
}
this.interceptorIndex = i;
}
}
return true;
}
// 调用每个拦截器的 PostHandler 方法。
void applyPostHandle(HttpServletRequest request, HttpServletResponse response, @Nullable ModelAndView mv)
throws Exception {
HandlerInterceptor[] interceptors = getInterceptors();
if (!ObjectUtils.isEmpty(interceptors)) {
for (int i = interceptors.length - 1; i >= 0; i--) {
HandlerInterceptor interceptor = interceptors[i];
interceptor.postHandle(request, response, this.handler, mv);
}
}
}
void triggerAfterCompletion(HttpServletRequest request, HttpServletResponse response, @Nullable Exception ex)
throws Exception {
HandlerInterceptor[] interceptors = getInterceptors();
if (!ObjectUtils.isEmpty(interceptors)) {
for (int i = this.interceptorIndex; i >= 0; i--) {
HandlerInterceptor interceptor = interceptors[i];
try {
interceptor.afterCompletion(request, response, this.handler, ex);
}
catch (Throwable ex2) {
logger.error("HandlerInterceptor.afterCompletion threw exception", ex2);
}
}
}
}
}
总结
整个处理流程
- 初始化 handlerAdapters 和 handlerMappings
- 根据 mappedHandler 从 handlerMappings 找到 mappedHandler
- 调用 mappedHandler 中每个拦截器的 PreHandler 方法。如果某个拦截器返回 false,请求处理就此完成。
- 调用 HandlerAdapter 的 handler 方法处理请求
- 生成 View
- 调用 mappedHandler 中每个拦截器的 PostHandler 方法
- 调用 mappedHandler 中每个拦截器的 triggerAfterCompletion 方法(即使有异常,该方法也确保执行)
所以整个处理流程的核心是 HandlerAdapter 的 handler 方法。关于 HandlerAdapter 的 handler 下篇文章详述。