SpringMVC到底是如何处理请求的?

很多人会用 SpringMVC,但对它的处理请求的方式并不清楚,当我们学习一个知识的时候,了解它会让我们更好地使用它,下面我们来看看 SpringMVC 是如何处理请求的。

请求流程的方式

先上图:

Spring MVC 框架也是一个基于请求驱动的 Web 框架,并且使用了前端控制器模式(是用来提供一个集中的请求处理机制,所有的请求都将由一个单一的处理程序处理来进行设计,再根据请求映射规则分发给相应的页面控制器(动作/处理器)进行处理。首先让我们整体看一下 Spring MVC 处理请求的流程:

首先用户发送请求,请求被 SpringMVC前端控制器(DispatherServlet)捕获;

前端控制器(DispatherServlet)对请求 URL 解析获取请求 URI,根据 URI,调用 HandlerMapping;

前端控制器(DispatherServlet)获得返回的 HandlerExecutionChain(包括 Handler 对象以及 Handler 对象对应的拦截器);

DispatcherServlet 根据获得的 HandlerExecutionChain,选择一个合适的 HandlerAdapter。(附注:如果成功获得 HandlerAdapter 后,此时将开始执行拦截器的 preHandler(...) 方法);

HandlerAdapter 根据请求的 Handler 适配并执行对应的 Handler;HandlerAdapter 提取 Request 中的模型数据,填充 Handler 入参,开始执行 Handler(Controller)。 在填充 Handler 的入参过程中,根据配置,Spring 将做一些额外的工作:

HttpMessageConveter:将请求消息(如 Json、xml 等数据)转换成一个对象,将对象转换为指定的响应信息;

数据转换:对请求消息进行数据转换。如 String 转换成 Integer、Double 等;

数据格式化:如将字符串转换成格式化数字或格式化日期等;

数据验证: 验证数据的有效性(长度、格式等),验证结果存储到 BindingResult 或 Error 中);

Handler 执行完毕,返回一个 ModelAndView (即模型和视图)给 HandlerAdaptor;

HandlerAdaptor 适配器将执行结果 ModelAndView 返回给前端控制器;

前端控制器接收到 ModelAndView 后,请求对应的视图解析器;

视图解析器解析 ModelAndView 后返回对应 View;

渲染视图并返回渲染后的视图给前端控制器;

最终前端控制器将渲染后的页面响应给用户或客户端。

案例实操

SpringMVC 请求执行源码解读

对于 SpringMVC 项目所有的请求入口(静态资源除外)这里都是从 web.xml 文件配置的前端控制器 DispatcherServlet 开始:


<servlet>

<servlet-name>springMvc</servlet-name>

<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

<init-param>

<param-name>contextConfigLocation</param-name>

<param-value>classpath:servlet-context.xml</param-value>

</init-param>


<load-on-startup>1</load-on-startup>

</servlet>

<servlet-mapping>

<servlet-name>springMvc</servlet-name>


<url-pattern>/</url-pattern>

</servlet-mapping>

DispatcherServlet UML继承关系图如下:

这里关注蓝线部分继承结构:DispatcherServlet-->FrameworkServlet-->HttpServletBean-->HttpServlet-->GenericServlet-->Servlet,对于请求核心时序图如下:

对于 web 请求的处理,大家都知道是通过继承 HttpServlet 重写其 service 方法,这里打开 DispatcherServlet 源码发现这里并没有看到我们要找的 service 方法,此时到父类 FrameworkServlet 查找如下:可以看到父类重写 HttpServlet service 方法。

FrameworkServlet#service

/**

* Override the parent class implementation in order to intercept PATCH requests.

*/

@Override

protected void service(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

HttpMethod httpMethod = HttpMethod.resolve(request.getMethod());

if (httpMethod == HttpMethod.PATCH || httpMethod == null) {

processRequest(request, response);

}

else {

super.service(request, response);

}

}

从源码分析来看当请求方法为 patch 请求或者为 null 时执行 processRequest0 方法,其他情况则调用父类 service 方法,大家都知道 SpringMVC 请求大多请求是 get|post 请求为主,此时继续向上查看 FrameworkServlet 父类 HttpServletBean(抽象类继承 HttpServlet 并未重写 service 方法,所以向上继续寻找)--> HttpServlet service 方法:

HttpServlet#service

@Override

public void service(ServletRequest req, ServletResponse res)

throws ServletException, IOException

{

HttpServletRequest  request;

HttpServletResponse response;

if (!(req instanceof HttpServletRequest &&

res instanceof HttpServletResponse)) {

throw new ServletException("non-HTTP request or response");

}

request = (HttpServletRequest) req;

response = (HttpServletResponse) res;

service(request, response);

}

}

protected void service(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException

{

String method = req.getMethod();

if (method.equals(METHOD_GET)) {

long lastModified = getLastModified(req);

if (lastModified == -1) {

// servlet doesn't support if-modified-since, no reason

// to go through further expensive logic

doGet(req, resp);

} else {

long ifModifiedSince = req.getDateHeader(HEADER_IFMODSINCE);

if (ifModifiedSince < lastModified) {

// If the servlet mod time is later, call doGet()

// Round down to the nearest second for a proper compare

// A ifModifiedSince of -1 will always be less

maybeSetLastModified(resp, lastModified);

doGet(req, resp);

} else {

resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);

}

}

} else if (method.equals(METHOD_HEAD)) {

long lastModified = getLastModified(req);

maybeSetLastModified(resp, lastModified);

doHead(req, resp);

} else if (method.equals(METHOD_POST)) {

doPost(req, resp);

} else if (method.equals(METHOD_PUT)) {

doPut(req, resp);

} else if (method.equals(METHOD_DELETE)) {

doDelete(req, resp);

} else if (method.equals(METHOD_OPTIONS)) {

doOptions(req,resp);

} else if (method.equals(METHOD_TRACE)) {

doTrace(req,resp);

} else {

//

// Note that this means NO servlet supports whatever

// method was requested, anywhere on this server.

//

String errMsg = lStrings.getString("http.method_not_implemented");

Object[] errArgs = new Object[1];

errArgs[0] = method;

errMsg = MessageFormat.format(errMsg, errArgs);

resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, errMsg);

}

}

可以看到 HttpServlet service 进行了重载,根据不同的请求类型然后调用不同处理方法,这里以 get 请求为例,当请求方法为 get 请求时在重载 service 方法中调用 doGet 方法进行处理,这里需要特别注意的是:HttpServlet 存在 doGet 方法实现,然而在继承的子类中也存在 doGet 方法实现,到底调用哪个方法?很明显调用子类的 doGet 方法(面向对象多态思想!!!)从继承 UML 关系图上看,最外层子类实现 doGet 方法的为 FrameworkServlet :

FrameworkServlet#doGet&processRequest

@Override

protected final void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

processRequest(request, response);

}

protected final void processRequest(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

// 系统计时开始时间

long startTime = System.currentTimeMillis();

Throwable failureCause = null;

// 国际化

LocaleContext previousLocaleContext = LocaleContextHolder.getLocaleContext();

LocaleContext localeContext = buildLocaleContext(request);

//构建ServletRequestAttributes对象

RequestAttributes previousAttributes = RequestContextHolder.getRequestAttributes();

ServletRequestAttributes requestAttributes = buildRequestAttributes(request, response, previousAttributes);

//异步管理

WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);

asyncManager.registerCallableInterceptor(FrameworkServlet.class.getName(), new RequestBindingInterceptor());

//初始化ContextHolders

initContextHolders(request, localeContext, requestAttributes);

try {

doService(request, response);

}

catch (ServletException | IOException ex) {

failureCause = ex;

throw ex;

}

catch (Throwable ex) {

failureCause = ex;

throw new NestedServletException("Request processing failed", ex);

}

finally {

//恢复原来的LocaleContext和ServiceRequestAttributes到LocaleContextHolder和RequestContextHolder,避免影响Servlet以外的处理,如Filter

resetContextHolders(request, previousLocaleContext, previousAttributes);

if (requestAttributes != null) {

requestAttributes.requestCompleted();

}

logResult(request, response, failureCause, asyncManager);

//发布ServletRequestHandlerEvent消息,这个请求是否执行成功都会发布消息的

publishRequestHandledEvent(request, response, startTime, failureCause);

}

}

// initContextHolders(request, localeContext, requestAttributes);

private void initContextHolders(HttpServletRequest request,

@Nullable LocaleContext localeContext, @Nullable RequestAttributes requestAttributes) {

if (localeContext != null) {

LocaleContextHolder.setLocaleContext(localeContext, this.threadContextInheritable);

}

if (requestAttributes != null) {

RequestContextHolder.setRequestAttributes(requestAttributes, this.threadContextInheritable);

}

}

该方法大概做了这几件事:国际化的设置,创建 ServletRequestAttributes 对象,初始化上下文 holders (即将 Request 对象放入到线程上下文中,如后续想要在方法中获取 request、response对象此时可以通过调用 LocaleContextHolder 对应方法即可),然后调用 doService 方法。对于 doService 方法,FrameworkServlet 类并未提供实现,该方法由 DispatcherServlet 子类实现:

DispatcherServlet#doService

DispatcherServlet 里面执行处理的入口方法是 doService,由于这个类继承于 FrameworkServlet 类,重写了 doService() 方法:

@Override

protected void doService(HttpServletRequest request, HttpServletResponse response) throws Exception {

logRequest(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 attributesSnapshot = null;

if (WebUtils.isIncludeRequest(request)) {

attributesSnapshot = new HashMap<>();

Enumeration attrNames = request.getAttributeNames();

while (attrNames.hasMoreElements()) {

String attrName = (String) attrNames.nextElement();

if (this.cleanupAfterInclude || attrName.startsWith(DEFAULT_STRATEGIES_PREFIX)) {

attributesSnapshot.put(attrName, request.getAttribute(attrName));

}

}

}

//Spring上下文

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());

//重定向的数据

if (this.flashMapManager != null) {

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 {

//request设置完相关的属性做真正的请求处理

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);

}

}

}

}

整个方法看下来处理的操作有:处理 include 标签的请求,将上下文放到 request 的属性中,将国际化解析器放到 request 的属性中,将主题解析器放到 request 属性中,将主题放到 request 的属性中,处理重定向的请求数据最后调用 doDispatch 这个核心的方法对请求进行处理:

DispatcherServlet#doDispatch

该方法是在 doService 方法中调用的,从底层设计了整个请求的处理流程:

根据 request 找到 Handler

根据 Handler 找到对应的 HandlerAdapter

用 HandlerAdapter 处理 Handler

调用 processDispatchResult 方法处理上面之后的结果(包含View渲染并输出给用户)

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 {

// 校验是否为上传请求 是上传请求执行解析 否则返回request

processedRequest = checkMultipart(request);

multipartRequestParsed = (processedRequest != request);

// 根据访问的Handler 返回指定对应的HandlerExecutionChain对象 这里从HandlerMapping 集合中查找 HandlerExecutionChain 对象包含Handler与拦截器HandlerInterceptor列表

mappedHandler = getHandler(processedRequest);

if (mappedHandler == null) {

noHandlerFound(processedRequest, response);

return;

}

// 根据得到的Handler 获取对应的HandlerAdaptor对象

HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());

// 处理GET、HEAD请求的Last-Modified

String method = request.getMethod();

boolean isGet = "GET".equals(method);

if (isGet || "HEAD".equals(method)) {

long lastModified = ha.getLastModified(request, mappedHandler.getHandler());

//当数据没有更改时,就直接返回上次的数据,提高效率

if (new ServletWebRequest(request, response).checkNotModified(lastModified) && isGet) {

return;

}

}

//执行Interceptor的preHandle 

if (!mappedHandler.applyPreHandle(processedRequest, response)) {

return;

}

// 执行Handler 返回ModelAndView

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

//如果需要异步处理,直接返回

if (asyncManager.isConcurrentHandlingStarted()) {

return;

}

//当view为空时,根据request设置默认view,如Handler返回值为void

applyDefaultViewName(processedRequest, mv);

//执行相应Interceptor的postHandle 

mappedHandler.applyPostHandle(processedRequest, response, mv);

}

catch (Exception ex) {

dispatchException = ex;

}

catch (Throwable err) {

// As of 4.3, we're processing Errors thrown from handler methods as well,

// making them available for @ExceptionHandler methods and other scenarios.

dispatchException = new NestedServletException("Handler dispatch failed", err);

}

//处理返回结果,包括处理异常、渲染页面,发出完成通知触发Interceptor的afterCompletion

processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException);

}

catch (Exception ex) {

triggerAfterCompletion(processedRequest, response, mappedHandler, ex);

}

catch (Throwable err) {

triggerAfterCompletion(processedRequest, response, mappedHandler,

new NestedServletException("Handler processing failed", 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);

}

}

}

}

doDispatcher 首先检查是不是上传请求,如果是则将 request 转换为 MultipartHttpServletRequest,并将 multipartRequestParsed 标志设置为 true;

通过 getHandler 获取 Handler 处理器链 HandlerExecutionChain;

处理GET、HEAD请求的 Last-Modified,这里主要判断 Last-Modified 值是否被修改来处理决定是否采用缓存数据;

接下来依次调用相应的 Interceptor 的 preHandle,执行拦截器拦截操作;

拦截器 preHandle 方法执行后,此时开始通过 HandlerAdapter 适配对应的 Handler 执行(这里才是真正要执行的 Controller 方法), Handler 处理完请求后,如果需要异步处理则直接返回,如果不需要异步处理,当 view 为空时,设置默认 view,然后执行相应的 Interceptor 的postHandle。

Handler:处理器,他直接对应着 MVC 中的 C,也就是 Controller 层,它的具体表现形式有很多,可以是类,也可以是方法(通常以方法居多),因为它的定义是 Object,我们在方法中标注的 @RequestMapping 的所有方法都可以看成一个 Handler,只要可以实际处理请求的都可以看成 Handler。

HandlerMapping:用来查找 Handler,在 SpringMVC 中会处理很多请求,每一个请求都需要一个 Handler 来处理,具体接受到请求后需要哪一个 Handler 来处理,此时通过 HandlerMapping 来实现查找。

HandlerAdapter:适配器,不同的 Handler 需要找到不同 HandlerAdapter 来调用 Handler。就如工厂里需要使用工具,工人(HandlerAdapter)使用工具(Handler)完成工作,而 HandlerMapping 用于根据需要完成的工作来找到相应的工具。

DispatcherServlet#processDispatchResult

processDispatchResult 方法主要用来处理前面返回的结果,其中包括处理异常、渲染页面、触发 Interceptor 的 afterCompletion 方法三部分内容,处理的异常是在处理请求 doDispatch 方法的过程中产生。

private void processDispatchResult(HttpServletRequest request, HttpServletResponse response,

@Nullable HandlerExecutionChain mappedHandler, @Nullable ModelAndView mv,

@Nullable Exception exception) throws Exception {

boolean errorView = false;

// 如果请求过程中有异常抛出则处理异常

if (exception != null) {

if (exception instanceof ModelAndViewDefiningException) {

logger.debug("ModelAndViewDefiningException encountered", exception);

mv = ((ModelAndViewDefiningException) exception).getModelAndView();

}

else {

Object handler = (mappedHandler != null ? mappedHandler.getHandler() : null);

mv = processHandlerException(request, response, handler, exception);

errorView = (mv != null);

}

}

//执行页面渲染操作

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;

}

// Handler请求处理完,触发Interceptor的afterCompletion

if (mappedHandler != null) {

// Exception (if any) is already handled..

mappedHandler.triggerAfterCompletion(request, response, null);

}

}

render 视图渲染:

protected void render(ModelAndView mv, HttpServletRequest request, HttpServletResponse response) throws Exception {

// Determine locale for request and apply it to the response.

Locale locale =

(this.localeResolver != null ? this.localeResolver.resolveLocale(request) : request.getLocale());

response.setLocale(locale);

View view;

String viewName = mv.getViewName();

if (viewName != null) {

// We need to resolve the view name.

view = resolveViewName(viewName, mv.getModelInternal(), locale, request);

if (view == null) {

throw new ServletException("Could not resolve view with name '" + mv.getViewName() +

"' in servlet with name '" + getServletName() + "'");

}

}

else {

// No need to lookup: the ModelAndView object contains the actual View object.

view = mv.getView();

if (view == null) {

throw new ServletException("ModelAndView [" + mv + "] neither contains a view name nor a " +

"View object in servlet with name '" + getServletName() + "'");

}

}

if (logger.isTraceEnabled()) {

logger.trace("Rendering view [" + view + "] ");

}

try {

if (mv.getStatus() != null) {

response.setStatus(mv.getStatus().value());

}

// 渲染页面处理

view.render(mv.getModelInternal(), request, response);

}

catch (Exception ex) {

if (logger.isDebugEnabled()) {

logger.debug("Error rendering view [" + view + "]", ex);

}

throw ex;

}

}

今天我们来了解了一下 SpringMVC 框架中 MVC 核心思想,SpringMVC 内部请求流程分析以及源码级别代码解读,让大家真正能够从底层级别理解整个框架执行原貌,最后以一张图来总结今天的源码分析执行流程。

扩展~MVC

模型-视图-控制器(MVC)是一个众所周知的以设计界面应用程序为基础的设计思想。它主要通过分离模型、视图及控制器在应用程序中的角色将业务逻辑从界面中解耦。通常,模型负责封装应用程序数据在视图层展示。视图仅仅只是展示这些数据,不包含任何业务逻辑。控制器负责接收来自用户的请求,并调用后台服务(service或者dao)来处理业务逻辑。处理后,后台业务层可能会返回了一些数据在视图层展示。控制器收集这些数据及准备模型在视图层展示。MVC模式的核心思想是将业务逻辑从界面中分离出来,允许它们单独改变而不会相互影响。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,402评论 6 499
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,377评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,483评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,165评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,176评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,146评论 1 297
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,032评论 3 417
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,896评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,311评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,536评论 2 332
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,696评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,413评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,008评论 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,659评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,815评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,698评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,592评论 2 353