前言
在DispatcherServlet初始化过程中,我们已经了解了DispatcherServlet的继承关系和初始化过程,现在我们继续学习下DispatcherServlet处理请求的整个过程,本篇文章我们不会讨论细节,特别是DispatcherServlet的处理细节,因为整个处理过程十分复杂,细节部分会留在后续的文章中分析。
Servlet
Servlet接口规定的请求的入口方法,即
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException;
GenericServlet
GenericServlet并没有具体实现service方法
public abstract void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException;
HttpServlet
HttpServlet是用HTTP协议实现的Servlet的基类,一般我们写的Servlet就是继承于它。
- 重写父类的service方法,把请求参数ServletRequest 、ServletResponse转化成HttpServletRequest、HttpServletResponse,然后调用内部方法
- 根据HTTP方法不同,路由到不同的doXXX方法中,doXXX方法由子类实现,子类没实现默认抛出异常。
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) {
doGet(req, resp);
} else {
long ifModifiedSince = req.getDateHeader(HEADER_IFMODSINCE);
if (ifModifiedSince < lastModified) {
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);
}
}
HttpServletBean
HttpServletBean主要参与创建工作,并没有涉及请求的处理。
FrameworkServlet
FrameworkServlet实现了doXXX的方法,内部交给processRequest(request, response)处理,以doGet为例,其代码如下
protected final void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
这里我们可以看出HttpServletBean把各种方法的请求重新聚集到processRequest方法集中处理,下面我们看下processRequest的处理过程,其简化代码如下
protected final void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
long startTime = System.currentTimeMillis();
Throwable failureCause = null;
// 获取LocaleContextHolder中保存的原始LocaleContext
LocaleContext previousLocaleContext = LocaleContextHolder.getLocaleContext();
// 创建当前请求的LocaleContext
LocaleContext localeContext = buildLocaleContext(request);
// 获取RequestContextHolder中保存的原始RequestAttributes
RequestAttributes previousAttributes = RequestContextHolder.getRequestAttributes();
// 创建当前请求的RequestAttributes
ServletRequestAttributes requestAttributes = buildRequestAttributes(request, response, previousAttributes);
WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
asyncManager.registerCallableInterceptor(FrameworkServlet.class.getName(), new FrameworkServlet.RequestBindingInterceptor());
//将localeContext、requestAttributes分别设置到LocaleContextHolder和RequestContextHolder
initContextHolders(request, localeContext, requestAttributes);
try {
// 模板方法,DispatcherServlet中实现
doService(request, response);
}
catch (ServletException ex) {
failureCause = ex;
throw ex;
}
catch (IOException ex) {
failureCause = ex;
throw ex;
}
catch (Throwable ex) {
failureCause = ex;
throw new NestedServletException("Request processing failed", ex);
}
finally {
// 恢复原来的LocaleContext和RequestAttributes
resetContextHolders(request, previousLocaleContext, previousAttributes);
if (requestAttributes != null) {
requestAttributes.requestCompleted();
}
// 发布ServletRequestHandledEvent消息
publishRequestHandledEvent(request, response, startTime, failureCause);
}
}
我们可以看出其中最重要的语句是doService(request, response),它是一个模板方法,具体实现在DispatcherServlet中。
DispatcherServlet
DispatcherServlet实现了doService方法,其简化代码如下
protected void doService(HttpServletRequest request, HttpServletResponse response) throws Exception {
// 当include请求时对request的attribute做快照备份
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(DEFAULT_STRATEGIES_PREFIX)) {
attributesSnapshot.put(attrName, request.getAttribute(attrName));
}
}
}
// 对request设置一些属性
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()) {
// 还原request的attribute属性
if (attributesSnapshot != null) {
restoreAttributesAfterInclude(request, attributesSnapshot);
}
}
}
}
我们可以看到整个过程的核心方法是doDispatch
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);
// 通过HandlerMapping得到HandlerExecutionChain,里面包括一组InterceptorHandler和一个Handler
mappedHandler = getHandler(processedRequest);
if (mappedHandler == null || mappedHandler.getHandler() == null) {
noHandlerFound(processedRequest, response);
return;
}
// 根据Handler找到HandlerAdapter
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 (logger.isDebugEnabled()) {
logger.debug("Last-Modified value for [" + getRequestUri(request) + "] is: " + lastModified);
}
if (new ServletWebRequest(request, response).checkNotModified(lastModified) && isGet) {
return;
}
}
// 执行相应Interceptor的preHandle
if (!mappedHandler.applyPreHandle(processedRequest, response)) {
return;
}
// HandlerAdapter处理请求
mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
if (asyncManager.isConcurrentHandlingStarted()) {
return;
}
// 当view为空时,根据request设置默认view
applyDefaultViewName(processedRequest, mv);
// 执行相应Interceptor的postHandle
mappedHandler.applyPostHandle(processedRequest, response, mv);
}
catch (Exception ex) {
dispatchException = ex;
}
catch (Throwable err) {
dispatchException = new NestedServletException("Handler dispatch failed", err);
}
// 处理返回结果,包括处理异常、渲染页面、发出完成通知和触发Interceptor的afterCompletion
processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException);
}
catch (Exception ex) {
// 执行相应Interceptor的afterCompletion
triggerAfterCompletion(processedRequest, response, mappedHandler, ex);
}
catch (Throwable err) {
// 执行相应Interceptor的afterCompletion
triggerAfterCompletion(processedRequest, response, mappedHandler,
new NestedServletException("Handler processing failed", err));
}
finally {
if (asyncManager.isConcurrentHandlingStarted()) {
if (mappedHandler != null) {
mappedHandler.applyAfterConcurrentHandlingStarted(processedRequest, response);
}
}
else {
if (multipartRequestParsed) {
cleanupMultipart(processedRequest);
}
}
}
}
下面我们再来看下processDispatchResult的处理过程
private void processDispatchResult(HttpServletRequest request, HttpServletResponse response,
HandlerExecutionChain mappedHandler, ModelAndView mv, Exception exception) throws Exception {
boolean errorView = false;
// 处理异常
if (exception != null) {
if (exception instanceof ModelAndViewDefiningException) {
mv = ((ModelAndViewDefiningException) exception).getModelAndView();
} else {
Object handler = (mappedHandler != null ? mappedHandler.getHandler() : null);
// 使用HandlerExceptionResolver处理异常
mv = processHandlerException(request, response, handler, exception);
errorView = (mv != null);
}
}
// 渲染视图
if (mv != null && !mv.wasCleared()) {
render(mv, request, response);
if (errorView) {
WebUtils.clearErrorRequestAttributes(request);
}
} else {
// log
}
if (WebAsyncUtils.getAsyncManager(request).isConcurrentHandlingStarted()) {
return;
}
// 执行相应Interceptor的afterCompletion
if (mappedHandler != null) {
mappedHandler.triggerAfterCompletion(request, response, null);
}
}
总结
下面用表格的形式简要总结下DispatcherServlet处理请求的过程
类或接口 | 处理请求入口方法 | 具体作用 |
---|---|---|
Servlet | service(ServletRequest req, ServletResponse res) | 接口定义,由Web容器调用 |
GenericServlet | service(ServletRequest req, ServletResponse res) | 抽象方法,没有实现 |
HttpServlet | service(ServletRequest req, ServletResponse res) | 根据HTTP方法不同,路由到不同的doXXX方法中 |
HttpServletBean | - | - |
FrameworkServlet | doXXX(HttpServletRequest request, HttpServletResponse response) | 把各种方法的请求重新聚集到processRequest方法集中处理,内部调用doService(HttpServletRequest request, HttpServletResponse response) |
DispatcherServlet | doService(HttpServletRequest request, HttpServletResponse response) | 调用内部方法doDispatch(HttpServletRequest request, HttpServletResponse response)具体处理请求 |