在之前的篇章中Spring MVC(1)
Spring MVC(2)我们了解了Spring mvc的DispatcherServelt的初始化,今天我们来看看DispatcherServlelt处理http请求的过程:
我们知道DispatcherServlet是一个Servlet,每一个Http请求都会调用service()方法的,那么我们从service方法开始:
DispatcherServlet的源码中我们没有找到service(ServletRequest req, ServletResponse res)这个方法,但是我们在DispatcherServlet的父类HttpServlet中找到了这个方法,我们去HttpServlet中看看这个方法的内容:
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这个方法的内容很简单,就是将ServletRequest和ServletResponse转换为HttpServletRequest和HttpServletResponse。因为我们是做web开发,通常用的是HTTP协议,所以这里我们需要的时候HttpServletRequest和HttpServletResponse。接下来就是调用service(HttpServletRequest request, HttpServletResponse response),我们在HttpServlet和FrameworkServlet中都找到了这个方法,但是HttpServlet是FrameworkServlet的父类,即FrameworkServlet中重写了service这个方法,所以我们这里取FrameworkServlet中去看看这个方法的内容:
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);
}
}
这个方法的第一步根据请求的方法类型转换对应的枚举类。如果请求类型为PATCH或者没有找到相应的请求类型的话,则直接调用processRequest这个方法。这里会执行super.service这个方法。即调用HttpServlet中的service方法。我们可以看一下HttpMethod这个枚举类:
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这个定义了这样的几种枚举类型:GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE;而这些也是RFC标准中几种请求类型。我们先看一下HttpServlet中这个service方法的内容:
3、HttpServlet中的Service(HttpServletRequest req, HttpServletResponse res)
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//获取请求类型
String method = req.getMethod();
//如果是get请求
if (method.equals(METHOD_GET)) {
//检查是不是开启了页面缓存 通过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
//没有开启页面缓存调用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);
//调用doGet方法
doGet(req, resp);
} else {
//设置304状态码 在HttpServletResponse中定义了很多常用的状态码
resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
}
}
} else if (method.equals(METHOD_HEAD)) {
//调用doHead方法
long lastModified = getLastModified(req);
maybeSetLastModified(resp, lastModified);
doHead(req, resp);
} else if (method.equals(METHOD_POST)) {
//调用doPost方法
doPost(req, resp);
} else if (method.equals(METHOD_PUT)) {
//调用doPost方法
doPut(req, resp);
} else if (method.equals(METHOD_DELETE)) {
//调用doPost方法
doDelete(req, resp);
} else if (method.equals(METHOD_OPTIONS)) {
//调用doPost方法
doOptions(req,resp);
} else if (method.equals(METHOD_TRACE)) {
//调用doPost方法
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);
}
}
这个方法的主要作用是根据请求类型调用响应的请求方法如果GET类型,调用doGet方法;POST类型,调用doPost方法。这些方法都是在HttpServlet中定义的,平时我们做web开发的时候主要是继承HttpServlet这个类,然后重写它的doPost或者doGet方法。我们的FrameworkServlet这个子类就重写了这些方法中的一部分: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中都直接调用processRequest方法,这个和步骤2中的请求类型为PATCH或者没有找到相应的请求类型的话,则直接调用processRequest这个方法。是同一个方法。那么我们来看看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();
//国际化
LocaleContext localeContext = buildLocaleContext(request);
RequestAttributes previousAttributes = RequestContextHolder.getRequestAttributes();
//构建ServletRequestAttributes对象
ServletRequestAttributes requestAttributes = buildRequestAttributes(request, response, previousAttributes);
//异步管理
WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
asyncManager.registerCallableInterceptor(FrameworkServlet.class.getName(), new RequestBindingInterceptor());
//初始化ContextHolders 和 resetContextHolders对其变更的内容还原操作
//主要是将Request请求、ServletRequestAttribute对象和国际化对象放入到上下文中
initContextHolders(request, localeContext, requestAttributes);
//执行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 {
//重新设置ContextHolders
//主要是将Request请求、ServletRequestAttribute对象和国际化对象还原为之前的值
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");
}
}
}
//发布请求处理事件
publishRequestHandledEvent(request, response, startTime, failureCause);
}
}
在这个方法里大概做了这样几件事:国际化的设置,创建ServletRequestAttributes对象,初始化上下文holders(即将Request对象放入到线程上下文中),调用doService方法。
5、DispatcherServlet中的doService:
@Override
protected void doService(HttpServletRequest request, HttpServletResponse response) throws Exception {
//如果是include请求,先保存一份request域数据的快照,doDispatch执行过后,将会用快照数据恢复。
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));
}
}
}
//设置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());
//设置重定向的数据
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方法-核心方法
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域数据的快照,doDispatch执行过后,将会用快照数据恢复。将国际化解析器放到request的属性中,将主题解析器放到request属性中,将主题放到request的属性中,处理重定向的请求数据,最后调用doDispatch这个核心的方法对请求进行处理,我们在下一章中详细分析一下doDispatch这个方法。
补充点东西:
RequestContextHolder这个类,有时候我们想在某些类中获取HttpServletRequest对象,比如在AOP拦截的类中,那么我们就可以这样来获取Request的对象了:
HttpServletRequest request = (HttpServletRequest) RequestContextHolder.getRequestAttributes().resolveReference(RequestAttributes.REFERENCE_REQUEST);
今天就先到这里 。。。。后续我们在看看doDispatch的代码
网友评论