spring mvc 原理分析

首先所有的请求都会提交到DispatcherServlet中 这是一个Servlet 继承了FrameworkServlet ,FrameworkServlet 继承了HttpServletBean , HttpServletBean 继承了HttpServlet 。


DispatcherServlet 中的doService方法

@Override
protected void doService(HttpServletRequest request, HttpServletResponse response) throws Exception {
if (logger.isDebugEnabled()) {
String resumed = WebAsyncUtils.getAsyncManager(request).hasConcurrentResult() ? " resumed" : "";
logger.debug("DispatcherServlet with name '" + getServletName() + "'" + resumed +
" processing " + request.getMethod() + " request for [" + getRequestUri(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<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));
}
}
}


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


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

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


// Determine handler for the current request.

mappedHandler = getHandler(processedRequest);//这个是根据HandlerMapping得到处理器链   

在这个方法中 会得到要执行的拦截器 和 要执行那个类中 controller 的方法

if (mappedHandler == null || mappedHandler.getHandler() == null) {
noHandlerFound(processedRequest, response);
return;
}


// Determine handler adapter for the current request.

HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());//根据handler 得到相应的适配器

//不同的适配器 处理的方法不一样的 ,所以必须要进行选择



// Process last-modified header, if supported by the handler.
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;
}
}


if (!mappedHandler.applyPreHandle(processedRequest, response)) {   //执行处理拦截器的pre方法 如果pre 中的方法返回false 那么 下面的代码就不会执行
return;
}


// Actually invoke the handler.
mv = ha.handle(processedRequest, response, mappedHandler.getHandler());//HandlerAdapter 适配器进行处理 返回一个modelView


if (asyncManager.isConcurrentHandlingStarted()) {
return;
}


applyDefaultViewName(processedRequest, mv); //是否要给一个默认的viewname

mappedHandler.applyPostHandle(processedRequest, response, mv); //执行拦截器的post 方法

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

processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException);//对视图进行渲染

//并执行拦截器的afterCompletion的方法
}
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);
}
}
}
}


猜你喜欢

转载自blog.csdn.net/hyhanyu/article/details/79649325
今日推荐