Java架构直通车——DispatcherServlet详解

2023-11-09


前文介绍了 Java架构直通车——理解Tomcat架构设计,我们知道Tomcat实际上就是Servlet容器,

引入

Spring MVC框架是围绕DispatcherServlet来设计的,这个Servlet会把请求分发给各个处理器,并支持可配置的处理器映射、视图渲染、本地化、时区与主题渲染和文件上传等功能。

Spring MVC框架是请求驱动的:所有设计都围绕着一个中央Servlet来展开,它负责把所有请求分发到控制器;同时提供其他Web应用开发所需要的功能。DispatcherServlet与Spring IoC容器做到了无缝集成,这意味着,Spring提供的任何特性在Spring MVC中你都可以使用。

DispatcherServlet处理流程

DispatcherServlet与WebApplicationContext

DispatcherServlet其实就是个Servlet(它继承自HttpServlet基类)。在Web MVC框架中,DispatcherServlet依赖于一个WebApplicationContext,这个context继承了WebApplicationContext的所有bean定义。继承的这些bean可以在每个servlet自己所属的域中被覆盖,覆盖的bean可以被设置成只有这个servlet实例自己才可以使用的属性。
在这里插入图片描述
WebApplicationContext是一个普通的ApplicationContext的扩展,它知道自己与哪个servlet相关联(通过ServletContext)。下面是WebApplicationContext所包含的bean
在这里插入图片描述

处理流程

在请求到来的时候,会在请求中查找并绑定 WebApplicationContext,它可以作为参数被控制器中的方法使用。 默认绑定到 DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE 对应的值。

处理流程不做赘述,参考:
再临SpringBoot——理解Spring Web Mvc架构处理流程
SpringMvc in Action——构建Sprig Web应用程序

DispatcherServlet源码分析

DispatcherServlet本质上还是一个Servlet。Servlet的生命周期大致分为三个阶段:

  1. 初始化阶段 init方法
  2. 处理请求阶段 service方法
  3. 结束阶段 destroy方法
public interface Servlet {
    public void init(ServletConfig config) throws ServletException;
    public void service(ServletRequest req, ServletResponse res)
            throws ServletException, IOException;
    public void destroy();
    
    public ServletConfig getServletConfig();
    public String getServletInfo();
}

这里就重点关注DispatcherServlet在这三个阶段具体做了那些工作。

init()

DispatcherServlet的init()的实现在其父类HttpServletBean中。

    public final void init() throws ServletException {
        ...
        // Set bean properties from init parameters.
        try {
            PropertyValues pvs = new ServletConfigPropertyValues(getServletConfig(), this.requiredProperties);
            BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this);
            ResourceLoader resourceLoader = new ServletContextResourceLoader(getServletContext());
            bw.registerCustomEditor(Resource.class, new ResourceEditor(resourceLoader, getEnvironment()));
            initBeanWrapper(bw);
            bw.setPropertyValues(pvs, true);
        }
        catch (BeansException ex) {
            logger.error("Failed to set bean properties on servlet '" + getServletName() + "'", ex);
            throw ex;
        }

        // Let subclasses do whatever initialization they like.
        initServletBean();

        ...
    }

以上部分源码描述的过程是通过读取的配置元素,读取到DispatcherServlet中,配置相关bean的配置。完成配置后调用initServletBean方法来创建Servlet WebApplicationContext

initServletBean方法在FrameworkServlet类中重写了:

    protected final void initServletBean() throws ServletException {
        ...

        try {
            this.webApplicationContext = initWebApplicationContext();
            initFrameworkServlet();
        }
        ...
    }
    
    protected WebApplicationContext initWebApplicationContext() {
        WebApplicationContext rootContext =
                WebApplicationContextUtils.getWebApplicationContext(getServletContext());
        WebApplicationContext wac = null;

        if (this.webApplicationContext != null) {
            wac = this.webApplicationContext;
            if (wac instanceof ConfigurableWebApplicationContext) {
                ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) wac;
                if (!cwac.isActive()) {
                    if (cwac.getParent() == null) {
                        cwac.setParent(rootContext);
                    }
                    configureAndRefreshWebApplicationContext(cwac);
                }
            }
        }
        if (wac == null) {
            wac = findWebApplicationContext();
        }
        if (wac == null) {
            wac = createWebApplicationContext(rootContext);
        }

        if (!this.refreshEventReceived) {
            onRefresh(wac);
        }

        if (this.publishContext) {
            String attrName = getServletContextAttributeName();
            getServletContext().setAttribute(attrName, wac);
            if (this.logger.isDebugEnabled()) {
                this.logger.debug("Published WebApplicationContext of servlet '" + getServletName() +
                        "' as ServletContext attribute with name [" + attrName + "]");
            }
        }

        return wac;
    }

service()

纵观SpringMVC的源码,大量运用模板方法的设计模式。Servlet的service方法也不例外。FrameworkServlet类重写service方法:

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        HttpMethod httpMethod = HttpMethod.resolve(request.getMethod());
        if (HttpMethod.PATCH == httpMethod || httpMethod == null) {
            processRequest(request, response);
        }
        else {
            super.service(request, response);
        }
    }

如果请求的方法是PATCH或者空,直接调用processRequest方法(后面会详细解释);否则,将调用父类的service的方法,即HttpServlet的service方法, 而这里会根据请求方法,去调用相应的doGet、doPost、doPut…

而doXXX系列方法的实现并不是HttpServlet类中,而是在FrameworkServlet类中。在FrameworkServlet中doXXX系列实现中,都调用了上面提到的processRequest方法

	protected final void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        long startTime = System.currentTimeMillis();
        Throwable failureCause = null;

        LocaleContext previousLocaleContext = LocaleContextHolder.getLocaleContext();
        LocaleContext localeContext = buildLocaleContext(request);

        RequestAttributes previousAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes requestAttributes = buildRequestAttributes(request, response, previousAttributes);

        WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
        asyncManager.registerCallableInterceptor(FrameworkServlet.class.getName(), new RequestBindingInterceptor());

        initContextHolders(request, localeContext, requestAttributes);

        try {
            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 {
            resetContextHolders(request, previousLocaleContext, previousAttributes);
            if (requestAttributes != null) {
                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");
                    }
                }
            }

            publishRequestHandledEvent(request, response, startTime, failureCause);
        }
    }

为了避免子类重写它,该方法用final修饰。

  1. 首先调用initContextHolders方法,将获取到的localeContextrequestAttributesrequest绑定到线程上。
  2. 然后调用doService方法,doService具体是由DispatcherServlet类实现的。
  3. doService执行完成后,调用resetContextHolders,解除localeContext等信息与线程的绑定。
  4. 最终调用publishRequestHandledEvent发布一个处理完成的事件。

DispatcherServlet类中的doService方法实现会调用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);
                if (mappedHandler == null || mappedHandler.getHandler() == null) {
                    noHandlerFound(processedRequest, response);
                    return;
                }

                // Determine handler adapter for the current request.
                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;
                    }
                }

                if (!mappedHandler.applyPreHandle(processedRequest, response)) {
                    return;
                }

                // Actually invoke the 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);
                }
            }
        }
    }

doDispatch主要流程是:

  1. 先判断是否Multipart类型的请求。如果是则通过multipartResolver解析request
  2. 通过getHandler方法找到从HandlerMapping 找到该请求对应的handler ,如果没有找到对应的handler则抛出异常。
  3. 通过getHandlerAdapter方法找到handler对应的HandlerAdapter
  4. 如果有拦截器,执行拦截器preHandler方法
  5. HandlerAdapter执行handle方法处理请求,返回ModelAndView
  6. 如果有拦截器,执行拦截器postHandle方法
  7. 然后调用processDispatchResult方法处理请求结果,封装到response中。

destroy()

destroy方法也是在FrameworkServlet里实现的,

	@Override
	public void destroy() {
		getServletContext().log("Destroying Spring FrameworkServlet '" + getServletName() + "'");
		// Only call close() on WebApplicationContext if locally managed...
		if (this.webApplicationContext instanceof ConfigurableApplicationContext && !this.webApplicationContextInjected) {
			((ConfigurableApplicationContext) this.webApplicationContext).close();
		}
	}

主要做了这么一个事:

	protected void doClose() {
		// Check whether an actual close attempt is necessary...
		if (this.active.get() && this.closed.compareAndSet(false, true)) {
			if (logger.isDebugEnabled()) {
				logger.debug("Closing " + this);
			}

			LiveBeansView.unregisterApplicationContext(this);

			try {
				// Publish shutdown event.
				publishEvent(new ContextClosedEvent(this));
			}
			catch (Throwable ex) {
				logger.warn("Exception thrown from ApplicationListener handling ContextClosedEvent", ex);
			}

			// Stop all Lifecycle beans, to avoid delays during individual destruction.
			if (this.lifecycleProcessor != null) {
				try {
					this.lifecycleProcessor.onClose();
				}
				catch (Throwable ex) {
					logger.warn("Exception thrown from LifecycleProcessor on context close", ex);
				}
			}

			// Destroy all cached singletons in the context's BeanFactory.
			destroyBeans();

			// Close the state of this context itself.
			closeBeanFactory();

			// Let subclasses do some final clean-up if they wish...
			onClose();

			// Reset local application listeners to pre-refresh state.
			if (this.earlyApplicationListeners != null) {
				this.applicationListeners.clear();
				this.applicationListeners.addAll(this.earlyApplicationListeners);
			}

			// Switch to inactive.
			this.active.set(false);
		}
	}

可以看到publishEvent、销毁了bean和beanFactory。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Java架构直通车——DispatcherServlet详解 的相关文章

  • react hooks useCallback useMemo的区别

    最近在看react hooks useState和useEffect较好理解 到useCallback和useMemo的时候 看官网不太懂 后来通过查阅资料 算是搞明白了 下面实例都是基于react native 不过原理和react是一样
  • Oracle ADG自动切换脚本分享

    为大家分享一个 Oracle ADG自动切换 的脚本 由云和恩墨工程师HongyeDBA编写 支持Switchover Failover 下载链接 https www modb pro download 5 DG环境需求 DG使用服务名必须

随机推荐

  • Python之匿名函数lambda使用方法

    文章目录 一 lambda函数介绍 1 1 语法 1 2 特性 1 3 示例 二 结合内置函数 map filter 使用 2 1 python内置的map 2 2 python内置的filter 一 lambda函数介绍 1 1 语法 在
  • golang面试题:json包变量不加tag会怎么样?

    问题 json包里使用的时候 结构体里的变量不加tag能不能正常转成json里的字段 怎么答 如果变量首字母小写 则为private 无论如何不能转 因为取不到反射信息 如果变量首字母大写 则为public 不加tag 可以正常转为json
  • Android 如何从活动向碎片传递数据

    踩了些坑 做个笔记 方便以后看 方法一 利用碎片的setArguments 方法传递bundle 首先 先穿插一个活动间传递数据的方法 活动间传递数据 两种方法 方法一 直接使用intent提供的put方法 如putString putpu
  • Java操作pdf的工具类itextpdf

    一 什么是iText 在企业的信息系统中 报表处理一直占比较重要的作用 iText是一种生成PDF报表的Java组件 通过在服务器端使用Jsp或JavaBean生成PDF报表 客户端采用超链接显示或下载得到生成的报表 这样就很好的解决了B
  • TS学习(二) :安装ts与ts配置

    一 安装TypeScript npm i g typescript 二 安装完成后 创建ts 使用ts语法 可能遇到的报错问题 在啥都没配置的默认情况下 TS会做出下面几种假设 假设当前的执行环境是dom 如果 代码中没有使用模块化语句 i
  • vscode-server离线安装及配置

    vscode server离线安装及配置 八字环 博客园 cnblogs com 获取当前版本vscode的commit id Help gt About gt Commit 根据commit id下载对应版本的vscode server
  • 保留IP地址

    保留IP地址不会在互联网中使用 其主要被用在企业机构内部作为局域网地址使用 例如 我们经常用到192 168 1 等 保留地址主要在以下四类 A类 10 0 0 0 10 255 255 255 长度相当于1个A类IP地址 A类 100 6
  • 在k8s集群中Kubernetes仪表板dashboard使用RABC机制限制指定用户针对指定名称空间中的资源进行管理实践...

    公众号关注 WeiyiGeek 设为 特别关注 每天带你玩转网络安全运维 应用开发 物联网IOT学习 本章目录 Dashboard 利用rbac机制限制指定用户针对指定名称空间中的资源进行UI管理 原文地址 https blog weiyi
  • 数据结构入门(二):顺序表

    目录 1 顺序表的概念 2 注意事项 3 接口的实现 4 顺序表的问题及思考 1 顺序表的概念 2 注意事项 在进行任意位置删除的时候 一定要注意是否越界 因为顺序表是以一个连续的线性表 3 接口的实现 3 1任意插入 头插和尾插 3 2任
  • \n,\r,\n\r的区别,windows、unix、mac中的换行区别

    转自 http www oschina net question 925405 132872 n 软回车 在Windows 中表示换行且回到下一行的最开始位置 相当于Mac OS 里的 r 的效果 在Linux unix 中只表示换行 但不
  • ALV FIELDCAT添加属性 – REUSE_ALV_FIELDCATALOG_MERGE函数

    在 ALV 定义 Fieldcat 的时候 我们往往需要通过 slis fieldcat alv 的赋值给Fieldcat导入结构 如上篇文章中给出的例子 01 02 03 04 05 06 07 08
  • sap doi技术操作excel的方法

    OLE是和微软OFFICE做接口 比较老的技术 DOI是SAP自己搞的 相对是后出来的技术 同样可以操作EXCEL 有一些方法 get sheets select range cell format set ranges format 等等
  • C语言itoa()函数和atoi()函数详解(整数转字符C实现)

    C语言提供了几个标准库函数 可以将任意类型 整型 长整型 浮点型等 的数字转换为字符串 1 int float to string array C语言提供了几个标准库函数 可以将任意类型 整型 长整型 浮点型等 的数字转换为字符串 下面列举
  • 2021年浙大软院推免机试题解和复试准备建议

    今年参加了浙江大学软件学院的推免复试 分为机试和面试 复试成绩 机试成绩 15 面试成绩 85 虽然机试占比不大 但是相对来说在取消PAT考试成绩抵机试后 机试的难度相比PAT甲级考试略大 同学之间的差距也会比较大 且机试成绩会影响面试老师
  • 【three.js练习程序】拖动选中的物体

  • SpringMVC DispatcherServlet源码(2) 扫描Controller创建HandlerMapping流程

    Spring MVC向容器注册一个RequestMappingInfoHandlerMapping组件 他会扫描容器中的Controller组件 创建RequestMappingInfo并注册HandlerMethod映射关系 本文将阅读S
  • ``三阶段:Vue的生命周期及相关信息``

    生命周期图 生命周期的钩子函数 beforeCreate 创建之前 预加载 里面没有数据 created 创建完成 数据请求 vue对象中东西都存在了 beforeMount 挂载之前 创建虚拟dom 没有渲染的 相关的虚拟dom优化 Mo
  • 韦东山: 作为一个初学者,怎样学习嵌入式Linux?

    被问过太多次 特写这篇文章来回答一下 在学习嵌入式Linux之前 肯定要有C语言基础 汇编基础有没有无所谓 就那么几条汇编指令 用到了一看就会 C语言要学到什么程度呢 越熟当然越好 不熟的话也要具备基本技能 比如写一个数组排序 输入数字求和
  • maven setting为什么需要配置镜像

    为什么需要配置maven国内镜像 1 在不配置镜像的情况下 maven默认会使用中央库 2 maven中央库在国外 有时候访问会很慢 尤其是下载较大的依赖的时候 有时候速度会很慢 甚至会出现无法下载的情况 3 为了解决依赖下载速度的问题 需
  • Java架构直通车——DispatcherServlet详解

    文章目录 引入 DispatcherServlet处理流程 DispatcherServlet与WebApplicationContext 处理流程 DispatcherServlet源码分析 init service destroy 前文