在之前的篇章中Spring MVC(1)
Spring MVC(2)我們了解了Spring mvc的DispatcherServelt的初始化,今天我們來看看DispatcherServlelt處理http請(qǐng)求的過程:
?我們知道DispatcherServlet是一個(gè)Servlet,每一個(gè)Http請(qǐng)求都會(huì)調(diào)用service()方法的,那么我們從service方法開始:
?DispatcherServlet的源碼中我們沒有找到service(ServletRequest req, ServletResponse res)這個(gè)方法,但是我們?cè)贒ispatcherServlet的父類HttpServlet中找到了這個(gè)方法,我們?nèi)ttpServlet中看看這個(gè)方法的內(nèi)容:
1、HttpServlet中的Service(ServletRequest req, ServletResponse res)方法:
@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("non-HTTP request or response");
}
service(request, response);
}
?service這個(gè)方法的內(nèi)容很簡(jiǎn)單,就是將ServletRequest和ServletResponse轉(zhuǎn)換為HttpServletRequest和HttpServletResponse。因?yàn)槲覀兪亲鰓eb開發(fā),通常用的是HTTP協(xié)議,所以這里我們需要的時(shí)候HttpServletRequest和HttpServletResponse。接下來就是調(diào)用service(HttpServletRequest request, HttpServletResponse response),我們?cè)贖ttpServlet和FrameworkServlet中都找到了這個(gè)方法,但是HttpServlet是FrameworkServlet的父類,即FrameworkServlet中重寫了service這個(gè)方法,所以我們這里取FrameworkServlet中去看看這個(gè)方法的內(nèi)容:
2、FrameworkServlet中的service(HttpServletRequest request, HttpServletResponse response):
@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);
}
}
?這個(gè)方法的第一步根據(jù)請(qǐng)求的方法類型轉(zhuǎn)換對(duì)應(yīng)的枚舉類。如果請(qǐng)求類型為PATCH或者沒有找到相應(yīng)的請(qǐng)求類型的話,則直接調(diào)用processRequest這個(gè)方法。這里會(huì)執(zhí)行super.service這個(gè)方法。即調(diào)用HttpServlet中的service方法。我們可以看一下HttpMethod這個(gè)枚舉類:
public enum HttpMethod {
GET,
HEAD,
POST,
PUT,
PATCH,
DELETE,
OPTIONS,
TRACE;
private static final Map<String, HttpMethod> mappings = new HashMap(8);
private HttpMethod() {
}
@Nullable
public static HttpMethod resolve(@Nullable String method) {
return method != null ? (HttpMethod)mappings.get(method) : null;
}
public boolean matches(String method) {
return this == resolve(method);
}
static {
HttpMethod[] var0 = values();
int var1 = var0.length;
for(int var2 = 0; var2 < var1; ++var2) {
HttpMethod httpMethod = var0[var2];
mappings.put(httpMethod.name(), httpMethod);
}
}
}
HttpMethod這個(gè)定義了這樣的幾種枚舉類型:GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE;而這些也是RFC標(biāo)準(zhǔn)中幾種請(qǐng)求類型。我們先看一下HttpServlet中這個(gè)service方法的內(nèi)容:
3、HttpServlet中的Service(HttpServletRequest req, HttpServletResponse res)
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//獲取請(qǐng)求類型
String method = req.getMethod();
//如果是get請(qǐng)求
if (method.equals(METHOD_GET)) {
//檢查是不是開啟了頁(yè)面緩存 通過header頭的 Last-Modified/If-Modified-Since
//獲取Last-Modified的值
long lastModified = getLastModified(req);
if (lastModified == -1) {
// servlet doesn't support if-modified-since, no reason
// to go through further expensive logic
//沒有開啟頁(yè)面緩存調(diào)用doGet方法
doGet(req, resp);
} else {
long ifModifiedSince;
try {
//獲取If-Modified-Since的值
ifModifiedSince = req.getDateHeader(HEADER_IFMODSINCE);
} catch (IllegalArgumentException iae) {
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
//更新Last-Modified
maybeSetLastModified(resp, lastModified);
//調(diào)用doGet方法
doGet(req, resp);
} else {
//設(shè)置304狀態(tài)碼 在HttpServletResponse中定義了很多常用的狀態(tài)碼
resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
}
}
} else if (method.equals(METHOD_HEAD)) {
//調(diào)用doHead方法
long lastModified = getLastModified(req);
maybeSetLastModified(resp, lastModified);
doHead(req, resp);
} else if (method.equals(METHOD_POST)) {
//調(diào)用doPost方法
doPost(req, resp);
} else if (method.equals(METHOD_PUT)) {
//調(diào)用doPost方法
doPut(req, resp);
} else if (method.equals(METHOD_DELETE)) {
//調(diào)用doPost方法
doDelete(req, resp);
} else if (method.equals(METHOD_OPTIONS)) {
//調(diào)用doPost方法
doOptions(req,resp);
} else if (method.equals(METHOD_TRACE)) {
//調(diào)用doPost方法
doTrace(req,resp);
} else {
//服務(wù)器不支持的方法 直接返回錯(cuò)誤信息
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);
}
}
?這個(gè)方法的主要作用是根據(jù)請(qǐng)求類型調(diào)用響應(yīng)的請(qǐng)求方法如果GET類型,調(diào)用doGet方法;POST類型,調(diào)用doPost方法。這些方法都是在HttpServlet中定義的,平時(shí)我們做web開發(fā)的時(shí)候主要是繼承HttpServlet這個(gè)類,然后重寫它的doPost或者doGet方法。我們的FrameworkServlet這個(gè)子類就重寫了這些方法中的一部分:doGet、doPost、doPut、doDelete、doOption、doTrace。
3、接著我們選擇性的看下FrameworkServlet中doGet/doPost方法:
@Override
protected final void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
protected final void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
這里我們可以看出FrameworkServlet中重寫了doGet、doPost、doDelete、doPut中都直接調(diào)用processRequest方法,這個(gè)和步驟2中的請(qǐng)求類型為PATCH或者沒有找到相應(yīng)的請(qǐng)求類型的話,則直接調(diào)用processRequest這個(gè)方法。是同一個(gè)方法。那么我們來看看processRequest方法:
4、FrameworkServlet中processRequest:
protected final void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
long startTime = System.currentTimeMillis();
Throwable failureCause = null;
LocaleContext previousLocaleContext = LocaleContextHolder.getLocaleContext();
//國(guó)際化
LocaleContext localeContext = buildLocaleContext(request);
RequestAttributes previousAttributes = RequestContextHolder.getRequestAttributes();
//構(gòu)建ServletRequestAttributes對(duì)象
ServletRequestAttributes requestAttributes = buildRequestAttributes(request, response, previousAttributes);
//異步管理
WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
asyncManager.registerCallableInterceptor(FrameworkServlet.class.getName(), new RequestBindingInterceptor());
//初始化ContextHolders 和 resetContextHolders對(duì)其變更的內(nèi)容還原操作
//主要是將Request請(qǐng)求、ServletRequestAttribute對(duì)象和國(guó)際化對(duì)象放入到上下文中
initContextHolders(request, localeContext, requestAttributes);
//執(zhí)行doService
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 {
//重新設(shè)置ContextHolders
//主要是將Request請(qǐng)求、ServletRequestAttribute對(duì)象和國(guó)際化對(duì)象還原為之前的值
resetContextHolders(request, previousLocaleContext, previousAttributes);
if (requestAttributes != null) {
requestAttributes.requestCompleted();
}
if (logger.isDebugEnabled()) {
if (failureCause != null) {
this.logger.debug("Could not complete request", failureCause);
}
else {
if (asyncManager.isConcurrentHandlingStarted()) {
logger.debug("Leaving response open for concurrent processing");
}
else {
this.logger.debug("Successfully completed request");
}
}
}
//發(fā)布請(qǐng)求處理事件
publishRequestHandledEvent(request, response, startTime, failureCause);
}
}
?在這個(gè)方法里大概做了這樣幾件事:國(guó)際化的設(shè)置,創(chuàng)建ServletRequestAttributes對(duì)象,初始化上下文holders(即將Request對(duì)象放入到線程上下文中),調(diào)用doService方法。
5、DispatcherServlet中的doService:
@Override
protected void doService(HttpServletRequest request, HttpServletResponse response) throws Exception {
//如果是include請(qǐng)求,先保存一份request域數(shù)據(jù)的快照,doDispatch執(zhí)行過后,將會(huì)用快照數(shù)據(jù)恢復(fù)。
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));
}
}
}
//設(shè)置Spring上下文
request.setAttribute(WEB_APPLICATION_CONTEXT_ATTRIBUTE, getWebApplicationContext());
//設(shè)置國(guó)際化解析器
request.setAttribute(LOCALE_RESOLVER_ATTRIBUTE, this.localeResolver);
//設(shè)置主題解析器
request.setAttribute(THEME_RESOLVER_ATTRIBUTE, this.themeResolver);
//設(shè)置主題
request.setAttribute(THEME_SOURCE_ATTRIBUTE, getThemeSource());
//設(shè)置重定向的數(shù)據(jù)
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 {
//調(diào)用doDispatch方法-核心方法
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);
}
}
}
}
?在這個(gè)方法中主要做了這幾件事:如果是include請(qǐng)求,先保存一份request域數(shù)據(jù)的快照,doDispatch執(zhí)行過后,將會(huì)用快照數(shù)據(jù)恢復(fù)。將國(guó)際化解析器放到request的屬性中,將主題解析器放到request屬性中,將主題放到request的屬性中,處理重定向的請(qǐng)求數(shù)據(jù),最后調(diào)用doDispatch這個(gè)核心的方法對(duì)請(qǐng)求進(jìn)行處理,我們?cè)谙乱徽轮性敿?xì)分析一下doDispatch這個(gè)方法。
補(bǔ)充點(diǎn)東西:
RequestContextHolder這個(gè)類,有時(shí)候我們想在某些類中獲取HttpServletRequest對(duì)象,比如在AOP攔截的類中,那么我們就可以這樣來獲取Request的對(duì)象了:
HttpServletRequest request = (HttpServletRequest) RequestContextHolder.getRequestAttributes().resolveReference(RequestAttributes.REFERENCE_REQUEST);
今天就先到這里 。。。。后續(xù)我們?cè)诳纯磀oDispatch的代碼