(3)Spring MVC请求分发部分源码分析

第一部分

  • Spring MVC所有的开始都会集中在Servlet上面,查看Spring MVC的源码,你会发现Servlet中的所有处理请求的方法(doGet、doPost...),最后都会委托给org.springframework.web.servlet.DispatcherServlet中的doDispatch(HttpServletRequest request, HttpServletResponse response)方法,而这个方法包含了一个请求从被分发,处理,通过HTTP返回浏览器数据(response.XXX)的所有逻辑,也就是说一个request的一生都会在这里度过。

  • 对于,核心代码,下面的源码中已经打上注释。可以先看第二部分,再看下面的源码,这里不再赘述。

  • spring mvc的拦截器严格上说不是责任链模式,但是就是责任链的思想,但比其更复杂。HandlerInterceptor带给我们的是一种具有高灵活性的细粒度的请求处理流程的拦截方案。

    /**
     * Process the actual dispatching to the handler.
     * 

The handler will be obtained by applying the servlet's HandlerMappings in order. * The HandlerAdapter will be obtained by querying the servlet's installed HandlerAdapters * to find the first that supports the handler class. *

All HTTP methods are handled by this method. It's up to HandlerAdapters or handlers * themselves to decide which methods are acceptable. * @param request current HTTP request * @param response current HTTP response * @throws Exception in case of any kind of processing failure */ protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception { WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request); try { try { processedRequest = checkMultipart(request); multipartRequestParsed = (processedRequest != request); // ★根据请求(HttpServletRequest)找到对应的HandlerExecutionChain //(包含该request对应的Handler和一系列拦截器HandlerInterceptor) mappedHandler = getHandler(processedRequest); if (mappedHandler == null || mappedHandler.getHandler() == null) { noHandlerFound(processedRequest, response); return; } // Determine handler adapter for the current request. //★找到Handler对应的适配器,方便DispatcherServlet了(正确调用Handler中的处理方法) HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler()); // 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; } } //★依次调用该request的所有拦截器的preHandler方法 if (!mappedHandler.applyPreHandle(processedRequest, response)) { return; } // Actually invoke the handler. //★真正开始调用Handler中的处理方法,即请求被分发到Handler中处理 mv = ha.handle(processedRequest, response, mappedHandler.getHandler()); if (asyncManager.isConcurrentHandlingStarted()) { return; } //★依次调用该request的所有拦截器的prePost方法 mappedHandler.applyPostHandle(processedRequest, response, mv); } 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); } //Handler的handle(...)执行后,返回ModelAndView后,这里主要的工作: //根据ModelAndView找到view,渲染,交给response返回 processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException); } }

第二部分

  • 1、首先看org.springframework.web.servlet.DispatcherServlet,里面有一个重要的成员变量handlerMappings。
    /** List of HandlerMappings used by this servlet */
    private List handlerMappings;

看到熟悉的HandlerMapping吧,我们知道这个接口,主要工作是帮助DispatcherServlet进行Web请求的URL到具体处理类的匹配。

/**
 * Interface to be implemented by objects that define a mapping between
 * requests and handler objects.
**/
public interface HandlerMapping {
    /**
     * Return a handler and any interceptors for this request. The choice may be made
     * on request URL, session state, or any factor the implementing class chooses.
     * 

The returned HandlerExecutionChain contains a handler Object, rather than * even a tag interface, so that handlers are not constrained in any way. * For example, a HandlerAdapter could be written to allow another framework's * handler objects to be used. *

Returns {@code null} if no match was found. This is not an error. * The DispatcherServlet will query all registered HandlerMapping beans to find * a match, and only decide there is an error if none can find a handler. * @param request current HTTP request * @return a HandlerExecutionChain instance containing handler object and * any interceptors, or {@code null} if no mapping found * @throws Exception if there is an internal error */ HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception;

  • 2、现在看看org.springframework.web.servlet.DispatcherServlet,根据请求找到具体的Handler(我们用的最多的Handler就是Controller)的getHandler(...)方法吧!
  • 我们在这个方法里面可以发现,会遍历所有的HandlerMapping,将为request找Handler委托给HandlerMapping,说白了,就是一个个试。如果找到就会返回一个HandlerExecutionChain.
    /**
     * Return the HandlerExecutionChain for this request.
     * 

Tries all handler mappings in order. * @param request current HTTP request * @return the HandlerExecutionChain, or {@code null} if no handler could be found */ protected HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception { for (HandlerMapping hm : this.handlerMappings) { if (logger.isTraceEnabled()) { logger.trace( "Testing handler map [" + hm + "] in DispatcherServlet with name '" + getServletName() + "'"); } HandlerExecutionChain handler = hm.getHandler(request); if (handler != null) { return handler; } } return null; }

  • 3、我们知道在Spring MVC中,任何可以用于Web请求处理的处理对象统称为Handler(Controller是Handler的一种特殊类型)。也就是可能会有很多类型的Handler那么org.springframework.web.servlet.DispatcherServlet是如何判断我们使用的是哪一种类型?又如何决定调用哪一个方法处理请求呢?
  • 我们会在org.springframework.web.servlet.DispatcherServlet发现这样一个成员变量。
    /** List of HandlerAdapters used by this servlet */
    private List handlerAdapters;
  • 这时,我们的HandlerAdapter就要登场了!它就是为了解决不同类型的Handler对DispatcherServlert造成的困扰而生的。

  • 每种Handler都应该有对应的HandlerAdapter,然后DispatcherHandler只要根据Handler,找到对应的HandlerAdapter,然后调用HandlerAdapter中的ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler)即可正确调用Handler中的处理方法。这部分逻辑在DispatcherServlet中的doDispatch(...)方法中。

// Determine handler adapter for the current request.
    HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());
...
// Actually invoke the handler.
    mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
public interface HandlerAdapter {

    /**
     * Given a handler instance, return whether or not this {@code HandlerAdapter}
     * can support it. Typical HandlerAdapters will base the decision on the handler
     * type. HandlerAdapters will usually only support one handler type each.
     * 

A typical implementation: *

{@code * return (handler instanceof MyHandler); * } * @param handler handler object to check * @return whether or not this object can use the given handler */ boolean supports(Object handler); /** * Use the given handler to handle this request. * The workflow that is required may vary widely. * @param request current HTTP request * @param response current HTTP response * @param handler handler to use. This object must have previously been passed * to the {@code supports} method of this interface, which must have * returned {@code true}. * @throws Exception in case of errors * @return ModelAndView object with the name of the view and the required * model data, or {@code null} if the request has been handled directly */ ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception; /** * Same contract as for HttpServlet's {@code getLastModified} method. * Can simply return -1 if there's no support in the handler class. * @param request current HTTP request * @param handler handler to use * @return the lastModified value for the given handler * @see javax.servlet.http.HttpServlet#getLastModified * @see org.springframework.web.servlet.mvc.LastModified#getLastModified */ long getLastModified(HttpServletRequest request, Object handler); }

最后看看org.springframework.web.servlet.DispatcherServlet中的getHandlerAdapter就会一目了然。

    /**
     * Return the HandlerAdapter for this handler object.
     * @param handler the handler object to find an adapter for
     * @throws ServletException if no HandlerAdapter can be found for the handler. This is a fatal error.
     */
    protected HandlerAdapter getHandlerAdapter(Object handler) throws ServletException {
        for (HandlerAdapter ha : this.handlerAdapters) {
            if (logger.isTraceEnabled()) {
                logger.trace("Testing handler adapter [" + ha + "]");
            }
            //判断该HandlerAdapter是否支持该Handler
            if (ha.supports(handler)) {
                return ha;
            }
        }
        throw new ServletException("No adapter for handler [" + handler +
                "]: The DispatcherServlet configuration needs to include a HandlerAdapter that supports this handler");
    }

  • 4.现在org.springframework.web.servlet.DispatcherServlet终于可以聪明的为每个request,找到对应的Handler了。

你可能感兴趣的:((3)Spring MVC请求分发部分源码分析)