SpringMVC中的DispatcherServlet請(qǐng)求分析
一、service請(qǐng)求(servlet請(qǐng)求轉(zhuǎn)換為Http請(qǐng)求)
DispatcherServlet作為一個(gè)Servlet,那么當(dāng)有請(qǐng)求到Tomcat等Servlet服務(wù)器時(shí),會(huì)調(diào)用其service方法。再調(diào)用到其父類GenericServlet的service方法,HttpServlet中實(shí)現(xiàn),如下(開(kāi)始請(qǐng)求的調(diào)用):
@Override
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException {
HttpServletRequest request;
HttpServletResponse response;
try {
request = (HttpServletRequest) req;
response = (HttpServletResponse) res;
} catch (ClassCastException e) {
throw new ServletException(lStrings.getString("http.non_http"));
}
service(request, response);
}HttpServlet層:將request和response類型進(jìn)行轉(zhuǎn)換后,繼續(xù)調(diào)用service方法:
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;
try {
ifModifiedSince = req.getDateHeader(HEADER_IFMODSINCE);
} catch (IllegalArgumentException iae) {
// Invalid date header - proceed as if none was set
ifModifiedSince = -1;
}
if (ifModifiedSince < (lastModified / 1000 * 1000)) {
// 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 {
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);
}
}根據(jù)調(diào)用的Http請(qǐng)求的方式,調(diào)用具體的底層(FrameworkServlet層)方法,get、post請(qǐng)求等都會(huì)有相同的處理,比如doGet如下:
@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);
RequestAttributes previousAttributes = RequestContextHolder.getRequestAttributes();
ServletRequestAttributes requestAttributes = buildRequestAttributes(request, response, previousAttributes);
WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
asyncManager.registerCallableInterceptor(FrameworkServlet.class.getName(), new RequestBindingInterceptor());
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 {
resetContextHolders(request, previousLocaleContext, previousAttributes);
if (requestAttributes != null) {
requestAttributes.requestCompleted();
}
logResult(request, response, failureCause, asyncManager);
publishRequestHandledEvent(request, response, startTime, failureCause);
}
}主要的核心邏輯為doService,但是Tomcat是使用線程池的方式接受來(lái)自客戶端的請(qǐng)求的,當(dāng)前請(qǐng)求中可能帶有Locate(國(guó)際化參數(shù)信息),那么需要使用ThreadLocal在請(qǐng)求前記錄參數(shù)信息,在請(qǐng)求之后finally中將參數(shù)恢復(fù)回去,不會(huì)影響到下一個(gè)請(qǐng)求。
Spring經(jīng)常會(huì)這樣進(jìn)行處理,比如AopContext等處理Aop切面信息。
二、doService請(qǐng)求(request中添加SpringMVC初始化的九大件信息)
@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<String, Object> 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));
}
}
}
// 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());
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 {
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);
}
}
}
}1、打印請(qǐng)求日志
2、請(qǐng)求中添加屬性(WebApplicationContext容器,i18n解析器,主題解析器,主題,重定向?qū)傩蕴幚恚?/p>
3、核心方法 doDispatch
三、doDispatch
protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
HttpServletRequest processedRequest = request;
HandlerExecutionChain mappedHandler = null;
boolean multipartRequestParsed = false;
// 異步請(qǐng)求屬性解析(重定向)
WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
try {
ModelAndView mv = null;
Exception dispatchException = null;
try {
// 如果是Multipart上傳文件請(qǐng)求,則調(diào)用multipartResolver.resolveMultipart(上傳文件解析器進(jìn)行解析)
processedRequest = checkMultipart(request);
multipartRequestParsed = (processedRequest != request);
// 確定Handler處理該請(qǐng)求(HandlerExecutionChain調(diào)用鏈,責(zé)任鏈模式)
mappedHandler = getHandler(processedRequest);
if (mappedHandler == null) {
noHandlerFound(processedRequest, response);
return;
}
// 根據(jù)初始化時(shí)加載的適配器挨個(gè)匹配是否能適配該調(diào)用鏈
HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());
// 對(duì)請(qǐng)求頭中的last-modified進(jìn)行處理
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;
}
}
// 對(duì)HandlerExecutionChain中的所有HandlerInterceptor調(diào)用preHandle方法
if (!mappedHandler.applyPreHandle(processedRequest, response)) {
return;
}
// 真正的請(qǐng)求調(diào)用
mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
if (asyncManager.isConcurrentHandlingStarted()) {
return;
}
// 判斷Controller返回的ModelAndView中是否有View,
// 沒(méi)有則使用viewNameTranslator執(zhí)行沒(méi)有試圖的解析規(guī)則
applyDefaultViewName(processedRequest, mv);
// 對(duì)HandlerExecutionChain中的所有HandlerInterceptor調(diào)用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);
}
// 處理結(jié)果解析(ModelAndView或者Exception),保證最終會(huì)執(zhí)行所以Interceptor的triggerAfterCompletion
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()) {
// 不知道什么情況下回進(jìn)入相當(dāng)于執(zhí)行所以Interceptor的postHandle和afterCompletion方法
if (mappedHandler != null) {
mappedHandler.applyAfterConcurrentHandlingStarted(processedRequest, response);
}
}
else {
// 清除當(dāng)前文件上傳請(qǐng)求的資源
if (multipartRequestParsed) {
cleanupMultipart(processedRequest);
}
}
}
}這里是整個(gè)SpringMVC的核心,每個(gè)流程都可能會(huì)比較復(fù)雜,后續(xù)單獨(dú)分析。流程如下(主要是標(biāo)紅的步驟):
1、異步請(qǐng)求屬性解析(重定向)
2、如果是Multipart上傳文件請(qǐng)求,則調(diào)用multipartResolver.resolveMultipart(上傳文件解析器進(jìn)行解析)
4、確定Handler處理該請(qǐng)求(HandlerExecutionChain調(diào)用鏈,責(zé)任鏈模式)
5、根據(jù)初始化時(shí)加載的適配器挨個(gè)匹配是否能適配該調(diào)用鏈
6、對(duì)請(qǐng)求頭中的last-modified進(jìn)行處理
7、對(duì)HandlerExecutionChain中的所有HandlerInterceptor調(diào)用preHandle方法
8、真正的請(qǐng)求調(diào)用
9、沒(méi)有試圖的解析返回
10、對(duì)HandlerExecutionChain中的所有HandlerInterceptor調(diào)用postHandle方法
11、處理結(jié)果解析(ModelAndView或者Exception),保證最終會(huì)執(zhí)行所以Interceptor的triggerAfterCompletion
12、清除當(dāng)前文件上傳請(qǐng)求的資源
HandlerInterceptor方法調(diào)用
當(dāng)我們需要使用Spring的攔截器時(shí),會(huì)集實(shí)現(xiàn)HandlerInterceptor的preHandle、postHandle、triggerAfterCompletion方法。
當(dāng)?shù)?步完成后我們獲取到了HandlerExecutionChain調(diào)用鏈,其中包括需要執(zhí)行的攔截器和真正調(diào)用的方法(后面專門分析專門獲取的)。
但是在上面的步驟看到了對(duì)攔截器的三個(gè)方法的調(diào)用時(shí)機(jī),其實(shí)每個(gè)調(diào)用的方法都差不多,就看preHandle方法即可,調(diào)用HandlerExecutionChain的applyPreHandle方法如下:
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;
}由于preHandle方法允許返回false則不執(zhí)行真實(shí)的Controller方法調(diào)用,所以需要每次判斷。但是在執(zhí)行preHandle和postHandle方法時(shí),都允許最后調(diào)用一次triggerAfterCompletion方法。都是在拿到調(diào)用鏈中的所以有序的攔截器,輪訓(xùn)調(diào)用其對(duì)應(yīng)的方法即可。
到此這篇關(guān)于SpringMVC中的DispatcherServlet請(qǐng)求分析的文章就介紹到這了,更多相關(guān)DispatcherServlet請(qǐng)求分析內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- SpringMVC中的DispatcherServlet結(jié)構(gòu)和初始化詳解
- SpringMVC中的DispatcherServlet初始化流程詳解
- SpringMVC之DispatcherServlet配置文件應(yīng)該放在哪里呢
- SpringMVC核心DispatcherServlet處理流程分步詳解
- spring boot 實(shí)現(xiàn)配置多個(gè)DispatcherServlet最簡(jiǎn)單方式
- Springmvc DispatcherServlet原理及用法解析
- Spring Boot全局異常處理機(jī)制中DispatcherServlet的處理流程和作用
相關(guān)文章
使用IDEA創(chuàng)建SpringBoot項(xiàng)目
本文詳細(xì)介紹了使用SpringBoot創(chuàng)建項(xiàng)目,包含配置、啟動(dòng)、開(kāi)發(fā)環(huán)境配置等,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2024-12-12
Java遞歸算法詳解(動(dòng)力節(jié)點(diǎn)整理)
Java遞歸算法是基于Java語(yǔ)言實(shí)現(xiàn)的遞歸算法。遞歸算法對(duì)解決一大類問(wèn)題很有效,它可以使算法簡(jiǎn)潔和易于理解。接下來(lái)通過(guò)本文給大家介紹Java遞歸算法相關(guān)知識(shí),感興趣的朋友一起學(xué)習(xí)吧2017-03-03
如何將java或javaweb項(xiàng)目打包為jar包或war包
本文主要介紹了如何將java或javaweb項(xiàng)目打包為jar包或war包,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-07-07
SpringBoot集成echarts實(shí)現(xiàn)k線圖功能
ECharts是一款基于JavaScript的數(shù)據(jù)可視化圖表庫(kù),提供直觀,生動(dòng),可交互,可個(gè)性化定制的數(shù)據(jù)可視化圖表,本文給大家介紹了SpringBoot集成echarts實(shí)現(xiàn)k線圖功能,文中有詳細(xì)的代碼示例供大家參考,需要的朋友可以參考下2024-07-07
SpringBoot后端進(jìn)行數(shù)據(jù)校驗(yàn)JSR303的使用詳解
這篇文章主要介紹了SpringBoot后端進(jìn)行數(shù)據(jù)校驗(yàn)JSR303的使用詳解,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-03-03

