Servletcontext,ApplicationContext和DispatcherServlet间的区别

简介: Servletcontext,ApplicationContext和DispatcherServlet间的区别


image.png

在springmvc中有很多概念,其中Servletcontext,ApplicationContext和DispatcherServlet是被提到最多的概念。下文将介绍这些概念的作用与区别。(spring boot中相同)

1.Servletcontext

说到Servletcontext,首先需要了解浏览器请求web的过程。

  1. 浏览器发送http请求到web容器。并将请求发送给tomcat等web容器。
  2. tomcat将http请求封装成httpServletRequest并发送给web项目。
    image.png
    而Servletcontext就是tomcat给web项目创建的全局环境。他有以下特点。
  3. 全局共享数据。
  4. 包含着web.xml里面的初始值。

2.ApplicationContext

在web.xml中,有以下代码。

 <listener>    
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>    
  </listener> 

我们可以点击进去看源代码。然后进入。

    @Override
  public void contextInitialized(ServletContextEvent event) {
    initWebApplicationContext(event.getServletContext());
  }

然后在点击进入。

     public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
    if (servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE) != null) {
      throw new IllegalStateException(
          "Cannot initialize context because there is already a root application context present - " +
          "check whether you have multiple ContextLoader* definitions in your web.xml!");
    }
    Log logger = LogFactory.getLog(ContextLoader.class);
    servletContext.log("Initializing Spring root WebApplicationContext");
    if (logger.isInfoEnabled()) {
      logger.info("Root WebApplicationContext: initialization started");
    }
    long startTime = System.currentTimeMillis();
    try {
      // Store context in local instance variable, to guarantee that
      // it is available on ServletContext shutdown.
      if (this.context == null) {
        this.context = createWebApplicationContext(servletContext);
      }
      if (this.context instanceof ConfigurableWebApplicationContext) {
        ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context;
        if (!cwac.isActive()) {
          // The context has not yet been refreshed -> provide services such as
          // setting the parent context, setting the application context id, etc
          if (cwac.getParent() == null) {
            // The context instance was injected without an explicit parent ->
            // determine parent for root web application context, if any.
            ApplicationContext parent = loadParentContext(servletContext);
            cwac.setParent(parent);
          }
          configureAndRefreshWebApplicationContext(cwac, servletContext);
        }
      }
      servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);
      ClassLoader ccl = Thread.currentThread().getContextClassLoader();
      if (ccl == ContextLoader.class.getClassLoader()) {
        currentContext = this.context;
      }
      else if (ccl != null) {
        currentContextPerThread.put(ccl, this.context);
      }
      if (logger.isDebugEnabled()) {
        logger.debug("Published root WebApplicationContext as ServletContext attribute with name [" +
            WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE + "]");
      }
      if (logger.isInfoEnabled()) {
        long elapsedTime = System.currentTimeMillis() - startTime;
        logger.info("Root WebApplicationContext: initialization completed in " + elapsedTime + " ms");
      }
      return this.context;
    }
    catch (RuntimeException ex) {
      logger.error("Context initialization failed", ex);
      servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex);
      throw ex;
    }
    catch (Error err) {
      logger.error("Context initialization failed", err);
      servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, err);
      throw err;
    }
  }

这段代码很简单,我们可以看到在servletContext中以key-value方式放入了一个WebApplicationContext对象,同时这也是spring的IOC环境。

servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);

3.DispatcherServlet

在进行以上流程之后,web.xml继续配置其他servlet,如DispatcherServlet(大家都拿这个举例。。。。),然后会找到WebApplicationContext。并把它作为自己的父上下文。并在WebApplicationContext中加载。

下图大概表明他们之间的关系。

image.png


相关文章
|
Java 数据库 Spring
【Spring】资源操作管理:Resource、ResourceLoader、ResourceLoaderAware;
【Spring】资源操作管理:Resource、ResourceLoader、ResourceLoaderAware;
470 1
|
SQL 关系型数据库 MySQL
MySQL删除数据后磁盘空间的释放总结
MySQL删除数据后磁盘空间的释放总结
2125 0
|
Java 测试技术 程序员
为什么Spring不推荐@Autowired用于字段注入?
作为Java程序员,Spring框架在日常开发中使用频繁,其依赖注入机制带来了极大的便利。然而,尽管@Autowired注解简化了依赖注入,Spring官方却不推荐在字段上使用它。本文将探讨字段注入的现状及其存在的问题,如难以进行单元测试、违反单一职责原则及易引发NPE等,并介绍为何Spring推荐构造器注入,包括增强代码可读性和维护性、方便单元测试以及避免NPE等问题。通过示例代码展示如何将字段注入重构为构造器注入,提高代码质量。
866 1
|
开发工具 Android开发
解决夜神模拟器与Android studio自动断开的问题
解决夜神模拟器与Android studio自动断开的问题
992 1
|
Java Maven Spring
springboot学习一:idea社区版本创建springboot项目的三种方式(第三种为主)
这篇文章介绍了在IntelliJ IDEA社区版中创建Spring Boot项目的三种方法,特别强调了第三种方法的详细步骤。
17777 0
springboot学习一:idea社区版本创建springboot项目的三种方式(第三种为主)
|
Java 应用服务中间件
idea文件右键创建New没有Create New Servlet的解决办法
idea文件右键创建New没有Create New Servlet的解决办法
idea文件右键创建New没有Create New Servlet的解决办法
|
Java 程序员 Spring
【小家Spring】资源访问利器---Spring使用ResourceLoader接口便捷的获取资源(ResourcePatternResolver、ResourceLoaderAware)(上)
【小家Spring】资源访问利器---Spring使用ResourceLoader接口便捷的获取资源(ResourcePatternResolver、ResourceLoaderAware)(上)
【小家Spring】资源访问利器---Spring使用ResourceLoader接口便捷的获取资源(ResourcePatternResolver、ResourceLoaderAware)(上)
|
搜索推荐
setContentType与setCharacterEncoding的区别
setCharacterEncoding只是设置字符的编码方式 setContentType除了可以设置字符的编码方式还能设置文档内容的·类型 1.setCharacterEncoding response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); out.print
1763 0
|
1天前
|
监控 网络协议 算法
2026年起SSL证书有效期逐年缩短:企业如何避免“续期风暴”!
SSL证书有效期将从2026年起分三阶段逐步缩短至47天,人工续期难以为继。阿里云“WoSign SSL证书+自动化服务”,支持域名监控、自动托管、云产品/服务器一键部署及智能提醒,助力企业高效应对高频续期挑战。
8058 2
|
10天前
|
域名解析 人工智能 Linux