spring mvc的dispatcherServlet(流程解析)

方法路径

org.springframework.web.servlet.DispatcherServlet#doDispatch

调用链解析

//根据请求url去map查找,返回一个封装了Interceptor数组和HandlerMethod的调用链对象
HandlerExecutionChain mappedHandler = getHandler(processedRequest);
//没找到直接走异常处理
if (mappedHandler == null) {
noHandlerFound(processedRequest, response);
return;
}
//根据获取到的HandlerMethod去map找能处理这个类型的HandlerMethod的HandlerAdapter
//如果没找到直接抛ServletException异常
HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());
//for循环调用HandlerExecutionChain中每个拦截器的preHandle方法
if (!mappedHandler.applyPreHandle(processedRequest, response)) {
return;
}
//用HandlerAdapter处理请求,如果响应直接写到response里面则返回值为空(如返回json给前端)
ModelAndView mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
//HandlerMethod方法执行完后,for循环调用HandlerExecutionChain中每个拦截器的postHandle方法
mappedHandler.applyPostHandle(processedRequest, response, mv);
//最后处理阶段,如果有异常且有配置全局异常处理器,则异常信息会直接写进response返回给前端
//如果有异常且配置了错误页面,则通过ViewResolver渲染一个视图写进response返回给前端
//如果controller方法中的返回是要求转发,则再调用一次doDispatch()
processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException);
//最后for循环调用HandlerExecutionChain中每个拦截器的afterCompletion方法
mappedHandler.triggerAfterCompletion(request, response, null);

spring boot 自动配置并创建dispatcherservlet

org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration

spring boot 注册dispatcherservlet调用链

org.springframework.context.support.AbstractApplicationContext#refresh
org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext#onRefresh
org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext#createWebServer
org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext#getSelfInitializer
org.springframework.boot.web.embedded.tomcat.TomcatWebServer#initialize
org.apache.catalina.util.LifecycleBase#startInternal
org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext#selfInitialize
org.springframework.boot.web.servlet.ServletContextInitializer#onStartup
org.springframework.boot.web.servlet.ServletRegistrationBean#addRegistration
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容