DispatcherServlet分析

初始化Servlet

初始化Servlet过程

HttpServletBean:  init
|
FrameworkServlet: initServletBean
|   
FrameworkServlet: initWebApplicationContext
|
DispatcherServlet: onRefresh
|
DispatcherServlet: initStrategies

初始化策略对象(以便servlet使用)

protected void initStrategies(ApplicationContext context) {
    // 文件上传解析器
    initMultipartResolver(context);
    // 本地化解析器
    initLocaleResolver(context);
    // 主题解析器
    initThemeResolver(context);
    // 处理器映射器(url和Controller方法的映射)
    initHandlerMappings(context);
    // 处理器适配器(实际执行Controller方法)
    initHandlerAdapters(context);
    // 处理器异常解析器
    initHandlerExceptionResolvers(context);
    // RequestToViewName解析器
    initRequestToViewNameTranslator(context);
    // 视图解析器(视图的匹配和渲染)
    initViewResolvers(context);
    // FlashMap管理者
    initFlashMapManager(context);
}

ApplicationContext获取HandlerMappings(以便servlet使用)

private void initHandlerMappings(ApplicationContext context) {
    this.handlerMappings = null;

    ...
	// Find all HandlerMappings in the ApplicationContext, including ancestor contexts.
	Map<String, HandlerMapping> matchingBeans =
			BeanFactoryUtils.beansOfTypeIncludingAncestors(context, HandlerMapping.class, true, false);
	if (!matchingBeans.isEmpty()) {
		this.handlerMappings = new ArrayList<>(matchingBeans.values());
		// We keep HandlerMappings in sorted order.
		AnnotationAwareOrderComparator.sort(this.handlerMappings);
	}
	...

}

请求过滤链

请求过滤链过程

ApplicationFilterChain: doFilter
ApplicationFilterChain: internalDoFilter
|
OncePerRequestFilter: doFilter
|
CharacterEncodingFilter: doFilterInternal
|
ApplicationFilterChain: doFilter
ApplicationFilterChain: internalDoFilter
|
OncePerRequestFilter: doFilter
|
HiddenHttpMethodFilter: doFilterInternal
|
ApplicationFilterChain: doFilter
ApplicationFilterChain: internalDoFilter
|
OncePerRequestFilter: doFilter
|
FormContentFilter: doFilterInternal
|
ApplicationFilterChain: doFilter
ApplicationFilterChain: internalDoFilter
|
OncePerRequestFilter: doFilter
|
RequestContextFilter: doFilterInternal
|
ApplicationFilterChain: doFilter
ApplicationFilterChain: internalDoFilter
|
WsFilter: doFilter
|
ApplicationFilterChain: doFilter
ApplicationFilterChain: internalDoFilter
|
HttpServlet: service
|
FrameworkServlet: service
|
HttpServlet: service
|
FrameworkServlet: doGet
|
FrameworkServlet: processRequest
|
DispatcherServlet: doService
|
DispatcherServlet: doDispatch

DispatcherServlet

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

            // 决定当前请求的Handler
            mappedHandler = getHandler(processedRequest);
            if (mappedHandler == null || mappedHandler.getHandler() == null) {
                noHandlerFound(processedRequest, response);
                return;
            }

            // 决定当前请求的HandlerAdapter
            HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());

            // 处理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;
                }
            }

            // 拦截器的前置处理
            if (!mappedHandler.applyPreHandle(processedRequest, response)) {
                return;
            }

            // Handler实际执行请求
            mv = ha.handle(processedRequest, response, mappedHandler.getHandler());

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

            // 设置默认视图名
            applyDefaultViewName(processedRequest, mv);
            // 拦截器后置处理
            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);
        }

        // 选择视图并渲染视图
        processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException);
    }
    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);
            }
        }
    }
}

Handler实际执行请求

DispatcherServlet: doDispatch
|
AbstractHandlerMethodAdapter: handle
|
RequestMappingHandlerAdapter: handleInternal
RequestMappingHandlerAdapter: invokeHandlerMethod
|
ServletInvocableHandlerMethod: invokeAndHandle
|
InvocableHandlerMethod: invokeForRequest
InvocableHandlerMethod: doInvoke

RequestMappingHandlerAdapter

protected ModelAndView invokeHandlerMethod(HttpServletRequest request, HttpServletResponse response, HandlerMethod handlerMethod) throws Exception {
    ServletWebRequest webRequest = new ServletWebRequest(request, response);
    Object result;
    try {
        WebDataBinderFactory binderFactory = this.getDataBinderFactory(handlerMethod);
        ModelFactory modelFactory = this.getModelFactory(handlerMethod, binderFactory);
        // controller下对应的调用 方法对象
        ServletInvocableHandlerMethod invocableMethod = this.createInvocableHandlerMethod(handlerMethod);
        invocableMethod.setHandlerMethodArgumentResolvers(this.argumentResolvers);
        invocableMethod.setHandlerMethodReturnValueHandlers(this.returnValueHandlers);
        invocableMethod.setDataBinderFactory(binderFactory);
        invocableMethod.setParameterNameDiscoverer(this.parameterNameDiscoverer);
        
        ...
        
        invocableMethod.invokeAndHandle(webRequest, mavContainer, new Object[0]);
        if (!asyncManager.isConcurrentHandlingStarted()) {
            ModelAndView var15 = this.getModelAndView(mavContainer, modelFactory, webRequest);
            return var15;
        }
        result = null;
    } finally {
        webRequest.requestCompleted();
    }
    return (ModelAndView)result;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值