SpringMVC-请求的处理流程

前文讲过,在SpringMVC中,对于请求的处理涉及到三个Servlet:HttpServletBean、FrameworkServlet和DispatcherServlet。

一、HttpServletBean

在SpringMVC的初始化过程中,HttpServletBean负责获取Servlet的配置参数,并放入SpringMVC的环境中,但在请求的处理上,HttpServletBean并没有做任何事情

二、FrameworkServlet

FrameworkServlet重新了HttpServlet的service()/doGet()/doPost()/doPut()/doDelete()/doOptions()/doTrace()方法,并在service方法中增加了对PATCH类型的处理

/**
     * Override the parent class implementation in order to intercept PATCH
     * requests.
     */
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String method = request.getMethod();
        if (method.equalsIgnoreCase(RequestMethod.PATCH.name())) {
            processRequest(request, response);
        }
        else {
            super.service(request, response);
        }
    }
//doGet()   
@Override
    protected final void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        processRequest(request, response);
    }

//doPost()
@Override
    protected final void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        processRequest(request, response);
    }

SpringMVC将请求汇总到了procesRequest()方法中。

在processRequest()中定义了SpringMVC处理请求的最外层框架,下面看一下具体的处理逻辑:

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 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 {
        //恢复RequestContextHolder和LocaleContextHolder中数据为最初的RequestAttributes和LocaleContext
            resetContextHolders(request, previousLocaleContext, previousAttributes);
            if (requestAttributes != null) {
    //标记SpringMVC对请求的处理完成
        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");
                    }
                }
            }
//向SpringMVC环境发布请求处理完成的事件
            publishRequestHandledEvent(request, response, startTime, failureCause);
        }
    }

从上面的代码中可以看出,FrameworkServlet实际上做了两件事:一是获取、设置最后恢复LocaleContextHolder和RequestContextHolder中的LocaleContext和RequestAttribute,二是发布代表处理已完成的ServletRequestHandledEvent事件。

其中LocaleContextHolder持有一个代表Locale信息的LocaleContext,RequestContextHolder持有一个封装了本次请求参数的RequestAttributes。

对于ServletRequestHandledEvent事件,我们可以利用ApplicationListener将其捕获,做一些额外的记录工作,例如请求日志

@Component
public class ServletRequestHandledEEventListener implements ApplicationListener<ServletRequestHandledEvent>{

    private static final Logger logger = LoggerFactory.getLogger(ServletRequestHandledEEventListener.class);

    @Override
    public void onApplicationEvent(ServletRequestHandledEvent event) {
        logger.info(event.getDescription());
    }

}

综上所述,FrameworkServlet首先是在service方法里添加了对PATCH的处理,并将所有需要自己处理的请求集中到了processRequest方法进行统一处理。然后,在processRequest中,首先从当前请求中获取LocaleContext和RequestAttributes并设置到LocaleContextHolder和RequestContextHolder中,然后调用doService()方法进入DispatcherServlet,最后恢复LocaleContextHolder和RequestContextHolder中的状态,并发布ServletRequestHandleEvent事件。

三、DispatcherServlet

从FrameworkServlet的processRequest()方法中,会进入到Dispatcher的doService()方法,看一下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 attributesSnapshot = null;
        /如果是include请求,则对request参数做快照
        if (WebUtils.isIncludeRequest(request)) {
            attributesSnapshot = new HashMap();
            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));
                }
            }
        }

        // 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/outputFlashMap)和FlashMapManager
        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);
                }
            }
        }
    }

从代码中可以看出,doService()首先判断是否是include请求,如果是则对request进行快照备份,并在最后恢复request到快照状态。最后将请求转到了doDispatcher()中。

那么,再来看一下doDispatcher()的处理逻辑:

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.
                //根据request找到对应的Handler
                mappedHandler = getHandler(processedRequest);
                if (mappedHandler == null || mappedHandler.getHandler() == null) {
                    noHandlerFound(processedRequest, response);
                    return;
                }

                // Determine handler adapter for the current request.
                //根据Handler找到HandlerAdapter
                HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());

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

                // Actually invoke the handler.
//HandlerAdapter利用Handler处理全给你求,并返回ModelAndView
                mv = ha.handle(processedRequest, response, mappedHandler.getHandler());

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

//当view为空时,根据request设置默认的view               applyDefaultViewName(request, mv);
//执行相应的Interceptor的postHandle方法             mappedHandler.applyPostHandle(processedRequest, response, mv);
            }
            catch (Exception ex) {
                dispatchException = ex;
            }
            //处理返回结果,包括异常处理,渲染页面等
            processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException);
        }
        catch (Exception ex) {
            triggerAfterCompletion(processedRequest, response, mappedHandler, ex);
        }
        catch (Error err) {
            triggerAfterCompletionWithError(processedRequest, response, mappedHandler, 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);
                }
            }
        }
    }

doDispatcher()从顶层设计了整个请求的处理过程:
1.根据request找到Handler;
2.根据Handler找到对应的HandlerAdapter;
3.用HandlerAdapter利用Handler处理请求;
4.调用processDispatchRequest方法处理ModelAndView

Handler:处理器,用来处理具体的请求。
HandlerMapping:根据具体的请求找到对应的Handler
HandlerAdapter:利用Handler来处理请求

在回到doDispatch()上来,大体分为两个部分:处理请求渲染页面

在doDispatch()中涉及几个变量:

HttpServletRequest processRequest:实际处理请求时所用到的request,如果不是上传请求则直接使用接收到的requet,否则将其封装为上传类型的request(StandardMultipartHttpServletRequest)

HandlerExecutionChain mappedHandler:处理请求的处理器链(包含处理器和对应的Interceptor)

boolean multipartRequestParsed:是不是上传请求的标志。

ModelAndView mv:封装Model和View的容器

Exception dispatcherException: 处理请求过程中发生的异常


你可能感兴趣的:(Code-Spring)