框架流程图

springmvc的核心类org.springframework.web.servlet.DispatcherServlet,是一个servlet,间接继承了httpservlet;重写了doService方法

@Override
protected void doService(HttpServletRequest request, HttpServletResponse response) throws Exception {
if (logger.isDebugEnabled()) {
String resumed = WebAsyncUtils.getAsyncManager(request).hasConcurrentResult() ? " resumed" : "";
logger.debug("DispatcherServlet with name '" + getServletName() + "'" + resumed +
" processing " + request.getMethod() + " request for [" + getRequestUri(request) + "]");
} // Keep a snapshot of the request attributes in case of an include,
// to be able to restore the original attributes after the include.
Map<String, Object> attributesSnapshot = null;
if (WebUtils.isIncludeRequest(request)) {
attributesSnapshot = new HashMap<String, Object>();
Enumeration<?> attrNames = request.getAttributeNames();
while (attrNames.hasMoreElements()) {
String attrName = (String) attrNames.nextElement();
if (this.cleanupAfterInclude || attrName.startsWith("org.springframework.web.servlet")) {
attributesSnapshot.put(attrName, request.getAttribute(attrName));
}
}
} // 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()); FlashMap inputFlashMap = this.flashMapManager.retrieveAndUpdate(request, response);
if (inputFlashMap != null) {
request.setAttribute(INPUT_FLASH_MAP_ATTRIBUTE, Collections.unmodifiableMap(inputFlashMap));
}
request.setAttribute(OUTPUT_FLASH_MAP_ATTRIBUTE, new FlashMap());
request.setAttribute(FLASH_MAP_MANAGER_ATTRIBUTE, this.flashMapManager); try {
doDispatch(request, response);
}
finally {
if (!WebAsyncUtils.getAsyncManager(request).isConcurrentHandlingStarted()) {
// Restore the original attribute snapshot, in case of an include.
if (attributesSnapshot != null) {
restoreAttributesAfterInclude(request, attributesSnapshot);
}
}
}
}

最重要的就是执行了 doDispatch(request, response);都只是对参数的处理

protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
HttpServletRequest processedRequest = request;
HandlerExecutionChain mappedHandler = null;
boolean multipartRequestParsed = false; WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request); try {
ModelAndView mv = null;
Exception dispatchException = null; try {
processedRequest = checkMultipart(request);
multipartRequestParsed = (processedRequest != request); //为当前请求确定处理器
mappedHandler = getHandler(processedRequest);
if (mappedHandler == null || mappedHandler.getHandler() == null) {
noHandlerFound(processedRequest, response);
return;
} //为当前请求确定处理程序适配器。
HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler()); // Process last-modified header, if supported by the handler.
String method = request.getMethod();
boolean isGet = "GET".equals(method);
if (isGet || "HEAD".equals(method)) {
long lastModified = ha.getLastModified(request, mappedHandler.getHandler());
if (logger.isDebugEnabled()) {
logger.debug("Last-Modified value for [" + getRequestUri(request) + "] is: " + lastModified);
}
if (new ServletWebRequest(request, response).checkNotModified(lastModified) && isGet) {
return;
}
}
          //执行所有拦截器的preHandle方法,如果有拦截器的prhandle方法返回false就直接结束,return
if (!mappedHandler.applyPreHandle(processedRequest, response)) {
return;
} // 由适配器调用实际的处理器
mv = ha.handle(processedRequest, response, mappedHandler.getHandler()); if (asyncManager.isConcurrentHandlingStarted()) {
return;
}
          //将逻辑路径转换为物理路径,将配置文件中配置的前缀和后缀拼接上返回的视图名字;
applyDefaultViewName(processedRequest, mv);
          //执行所有拦截器的postHandle方法
mappedHandler.applyPostHandle(processedRequest, response, mv);
}
catch (Exception ex) {
dispatchException = ex;
}
processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException);
}
catch (Exception ex) {
triggerAfterCompletion(processedRequest, response, mappedHandler, ex);
}
catch (Error err) {
triggerAfterCompletionWithError(processedRequest, response, mappedHandler, err);
}
finally {
if (asyncManager.isConcurrentHandlingStarted()) {
// Instead of postHandle and afterCompletion
if (mappedHandler != null) {
mappedHandler.applyAfterConcurrentHandlingStarted(processedRequest, response);
}
}
else {
// Clean up any resources used by a multipart request.
if (multipartRequestParsed) {
cleanupMultipart(processedRequest);
}
}
}
}

一 首先前端控制器获取到请求,首先获取到请求有没有文件的上传,调用方法

processedRequest = checkMultipart(request);

protected HttpServletRequest checkMultipart(HttpServletRequest request) throws MultipartException {
if (this.multipartResolver != null && this.multipartResolver.isMultipart(request)) {
if (WebUtils.getNativeRequest(request, MultipartHttpServletRequest.class) != null) {
logger.debug("Request is already a MultipartHttpServletRequest - if not in a forward, " +
"this typically results from an additional MultipartFilter in web.xml");
}
else if (request.getAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE) instanceof MultipartException) {
logger.debug("Multipart resolution failed for current request before - " +
"skipping re-resolution for undisturbed error rendering");
}
else {
return this.multipartResolver.resolveMultipart(request);
}
}
// If not returned before: return original request.
return request;
}

二.然后调用mappedHandler = getHandler(processedRequest),在这个方法中再调用处理器映射器的getHandler(processedRequest)方法

1.遍历所有的处理器映射器,

2.获取到xml中配置的处理器映射器,或者没有配置使用默认的处理器映射器;

3.然后有处理器映射器调用getHandler(request)方法,返回处理器执行链

      3.1通过url获取处理器,如果获取不到,就会走默认的处理器,如果还没有,就返回null;

      3.2同时看处理器是否是字符串,如果是字符串就通这个字符串去spring工厂中找到这个处理器

      43.3然后通过处理器获取到处理器执行链,然后返回处理器执行链(包含处理器,拦截器链,拦截器prehander方法执行到那一个拦截器在拦截器链中的下标)

    protected HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
for (HandlerMapping hm : this.handlerMappings) {
if (logger.isTraceEnabled()) {
logger.trace(
"Testing handler map [" + hm + "] in DispatcherServlet with name '" + getServletName() + "'");
}
HandlerExecutionChain handler = hm.getHandler(request);
if (handler != null) {
return handler;
}
}
return null;
}
public final HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
Object handler = getHandlerInternal(request);
if (handler == null) {
handler = getDefaultHandler();
}
if (handler == null) {
return null;
}
// Bean name or resolved handler?
if (handler instanceof String) {
String handlerName = (String) handler;
handler = getApplicationContext().getBean(handlerName);
} HandlerExecutionChain executionChain = getHandlerExecutionChain(handler, request);
if (CorsUtils.isCorsRequest(request)) {
CorsConfiguration globalConfig = this.corsConfigSource.getCorsConfiguration(request);
CorsConfiguration handlerConfig = getCorsConfiguration(handler, request);
CorsConfiguration config = (globalConfig != null ? globalConfig.combine(handlerConfig) : handlerConfig);
executionChain = getCorsHandlerExecutionChain(request, executionChain, config);
}
return executionChain;
}

三.通过处理器执行链(HandlerExecutionChain)找到对应的处理器适配器(HandlerAdapter)

调用HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler())

protected HandlerAdapter getHandlerAdapter(Object handler) throws ServletException {
for (HandlerAdapter ha : this.handlerAdapters) {
if (logger.isTraceEnabled()) {
logger.trace("Testing handler adapter [" + ha + "]");
}
if (ha.supports(handler)) {
return ha;
}
}
throw new ServletException("No adapter for handler [" + handler +
"]: The DispatcherServlet configuration needs to include a HandlerAdapter that supports this handler");
}

四:执行处理器执行链中的applyPreHandle(processedRequest, response)方法,并且进行了判断,是false就直接return

if (!mappedHandler.applyPreHandle(processedRequest, response)) {
return;
}

applyPreHandle(processedRequest, response)方法:

1.循环执行处理器执行链中的拦截器链的preHandle方法,如果都没有拦截,就直接走下一步

2.如果有拦截器拦截了,

    2-1.preHandle方法返回了false,就记录下这个拦截器的前一个的下标,就是记录所有已经执行了prehandler方法返回true的拦截器,

    2-2.然后遍历已经执行了prehandler方法返回true的拦截器,再执行他们的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;
}

所以当有拦截器拦截了时,就不执行下面的代码了,直接return,但是在return之前会执行已经执行了prehandler方法返回true的拦截器的afterCompletion方法

当没有拦截器拦截时执行

六:通过适配器执行处理器,并且返回一个ModelAndView,模型视图对象

mv = ha.handle(processedRequest, response, mappedHandler.getHandler());

七:然后将ModelAndView传递给ViewResolver视图解析器,将逻辑视图转换为物理视图,就是拼接xml中的配置的前缀和后缀,然后返回一个视图对象

applyDefaultViewName(processedRequest, mv);
private void applyDefaultViewName(HttpServletRequest request, ModelAndView mv) throws Exception {
if (mv != null && !mv.hasView()) {
mv.setViewName(getDefaultViewName(request));
}
}
protected String getDefaultViewName(HttpServletRequest request) throws Exception {
return this.viewNameTranslator.getViewName(request);
}
public String getViewName(HttpServletRequest request) {
String lookupPath = this.urlPathHelper.getLookupPathForRequest(request);
return (this.prefix + transformPath(lookupPath) + this.suffix);
}

八:mappedHandler.applyPostHandle(processedRequest, response, mv);执行所有拦截器的postHandler方法,并且遍历是逆序遍历的,所以后配置的会先执行postHandler方法

void applyPostHandle(HttpServletRequest request, HttpServletResponse response, 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);
}
}
}

九都是捕获异常的操作,捕获到异常之后最后还是会执行已经执行了prehandler方法返回true的拦截器的afterCompletion方法

catch (Exception ex) {
triggerAfterCompletion(processedRequest, response, mappedHandler, ex);
}
catch (Error err) {
triggerAfterCompletionWithError(processedRequest, response, mappedHandler, err);
}
private void triggerAfterCompletion(HttpServletRequest request, HttpServletResponse response,
HandlerExecutionChain mappedHandler, Exception ex) throws Exception { if (mappedHandler != null) {
mappedHandler.triggerAfterCompletion(request, response, ex);
}
throw ex;
} private void triggerAfterCompletionWithError(HttpServletRequest request, HttpServletResponse response,
HandlerExecutionChain mappedHandler, Error error) throws Exception { ServletException ex = new NestedServletException("Handler processing failed", error);
if (mappedHandler != null) {
mappedHandler.triggerAfterCompletion(request, response, ex);
}
throw ex;
}
void triggerAfterCompletion(HttpServletRequest request, HttpServletResponse response, 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);
}
}
}
}

最后就是对如果是文件上传的话,进行关流等操作

finally {
if (asyncManager.isConcurrentHandlingStarted()) {
// Instead of postHandle and afterCompletion
if (mappedHandler != null) {
mappedHandler.applyAfterConcurrentHandlingStarted(processedRequest, response);
}
}
else {
// Clean up any resources used by a multipart request.
if (multipartRequestParsed) {
cleanupMultipart(processedRequest);
}
}
}

springmvc简单的流程说明及源码分析的更多相关文章

  1. 面试高频SpringMVC执行流程最优解(源码分析)

    文章已托管到GitHub,大家可以去GitHub查看阅读,欢迎老板们前来Star! 搜索关注微信公众号 码出Offer 领取各种学习资料! SpringMVC执行流程 SpringMVC概述 Spri ...

  2. SpringMVC视图机制详解[附带源码分析]

    目录 前言 重要接口和类介绍 源码分析 编码自定义的ViewResolver 总结 参考资料 前言 SpringMVC是目前主流的Web MVC框架之一. 如果有同学对它不熟悉,那么请参考它的入门bl ...

  3. SpringMVC拦截器详解[附带源码分析]

    目录 前言 重要接口及类介绍 源码分析 拦截器的配置 编写自定义的拦截器 总结 总结 前言 SpringMVC是目前主流的Web MVC框架之一. 如果有同学对它不熟悉,那么请参考它的入门blog:h ...

  4. SpringMVC异常处理机制详解[附带源码分析]

    目录 前言 重要接口和类介绍 HandlerExceptionResolver接口 AbstractHandlerExceptionResolver抽象类 AbstractHandlerMethodE ...

  5. 基于vue实现一个简单的MVVM框架(源码分析)

    不知不觉接触前端的时间已经过去半年了,越来越发觉对知识的学习不应该只停留在会用的层面,这在我学jQuery的一段时间后便有这样的体会. 虽然jQuery只是一个JS的代码库,只要会一些JS的基本操作学 ...

  6. [转]SpringMVC拦截器详解[附带源码分析]

      目录 前言 重要接口及类介绍 源码分析 拦截器的配置 编写自定义的拦截器 总结 前言 SpringMVC是目前主流的Web MVC框架之一. 如果有同学对它不熟悉,那么请参考它的入门blog:ht ...

  7. SpringMVC拦截器详解[附带源码分析](转)

    本文转自http://www.cnblogs.com/fangjian0423/p/springMVC-interceptor.html 感谢作者 目录 前言 重要接口及类介绍 源码分析 拦截器的配置 ...

  8. Django drf:序列化增删改查、局部与全局钩子源码流程、认证源码分析、执行流程

    一.序列化类的增.删.改.查 用drf的序列化组件   -定义一个类继承class BookSerializer(serializers.Serializer):   -写字段,如果不指定source ...

  9. Flask - 请求处理流程和上下文源码分析

    目录 Flask - 请求处理流程和上下文 WSGI Flask的上下文对象及源码解析 0. 请求入口 1.请求上下文对象的创建 2. 将请求上下文和应用上下文入栈 3.根据请求的URl执行响应的视图 ...

随机推荐

  1. 信号报告-python

    #Signal report.py a = eval(input()) #这里要整除 readability = a // 10 strength = a - readability * 10 # p ...

  2. 【EMV L2】Application Usage Control

    [Application Usage Control] Tag9F07,卡片数据,2bytes: Indicates issuer’s specified restrictions on the ge ...

  3. CSS学习笔记_day3

    一.浮动的清除 1.给祖先元素加高度 <style> * { padding: 0; margin: 0; } .box1 { height: 100px; /**/ } ul { /*去 ...

  4. angular6 开发实践基础知识汇总

    1 事件处理 1.1   鼠标移入事件触发 (mouseenter)=" "               eg:   (mouseenter)="isCollapsed= ...

  5. OSI七层网络模型浅析

    OSI七层网络模型(从下往上): 物理层(Physical):设备之间的数据通信提供传输媒体及互连设备,为数据传输提供可靠的 环境.可以理解为网络传输的物理媒体部分,比如网卡,网线,集线器,中继器,调 ...

  6. 谈一谈socket与java

    用java中socket实现socket聊天 1,      什么是socket Socket 是指网络套接字,什么是套接字呢?    这是网络上一种端对端的网络协议,端口就是进程号,socket在网 ...

  7. BInsertSort

    #include <bits/stdc++.h> using namespace std; #define MAXSIZE 200000 typedef int KeyType; type ...

  8. [工作积累] Google Play Services

    注意添加APP_ID <meta-data android:name="com.google.android.gms.games.APP_ID" android:value= ...

  9. 谷歌chrome浏览器vue调试工具vue-devtools的安装

    先导 vue-devtools是一款基于chrome浏览器的插件,用于vue应用的调试,这款vue调试神器可以极大地提高我们的调试效率.帮助我们快速的调试开发vue应用. 第一步: 我们可以先从git ...

  10. VMware Workstation Pro 安装win7系统

    1.准备工作VMware Workstation Pro 虚拟机软件cn_windows_7_enterprise_x64_dvd_x15-70741.iso2.选择典型(推荐)(T) 单选按钮 3. ...