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 数据库连接 mybatis
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception
在进行springboot和mybatis遇到了这个错误 Servlet.service() for servlet [dispatcherServlet] in context with path [] th
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception
|
存储 Java 应用服务中间件
SpringMVC源码分析 DispatcherServlet源码分析
SpringMVC源码分析 DispatcherServlet源码分析
SpringMVC源码分析 DispatcherServlet源码分析
|
XML 存储 前端开发
02创建DispatcherServlet来处理所有的请求
1.Servlet的生命周期 2.DispatcherServlet的类结构体系 3.让DispatcherServlet来处理所有的请求
231 0
|
前端开发
DispatcherServlet源码注解分析
DispatcherServlet源码注解分析
133 0
|
前端开发 Java Spring
【小家Spring】Spring MVC执行流程 FrameworkServlet、DispatcherServlet源码分析(processRequest、doDispatch)(中)
【小家Spring】Spring MVC执行流程 FrameworkServlet、DispatcherServlet源码分析(processRequest、doDispatch)(中)
|
设计模式 开发框架 前端开发
SpringMVC源码解析DispatcherServlet#doDispatch方法流程(上)
SpringMVC源码解析DispatcherServlet#doDispatch方法流程(上)
225 0
SpringMVC源码解析DispatcherServlet#doDispatch方法流程(上)
SpringMVC源码解析DispatcherServlet#doDispatch方法流程(下)
SpringMVC源码解析DispatcherServlet#doDispatch方法流程(下)
154 0
SpringMVC源码解析DispatcherServlet#doDispatch方法流程(下)
|
XML 前端开发 Java
SpringMVC之context-dispatcher.xml,了解基本的控制器
SpringMVC之context-dispatcher.xml,了解基本的控制器
135 0
SpringMVC之context-dispatcher.xml,了解基本的控制器
|
Java 容器 Spring
DispatcherServlet
路径 org.springframework.web.servlet.DispatcherServlet 继承关系 重点关注doService()方法 该方法重写了父类FrameworkServlet的方法 FrameworkServlet在processRequest()方法中调用了...
798 0
|
前端开发 Java Spring
DispatcherServlet源码分析
DispatcherServlet处理request DispatcherServlet是前端控制器, Spring MVC遵循前端控制器模式,前端控制器是MVC 模式中C的一部分, 除此之外,C还包括我们定义的Controller等应用控制器类。
732 0

热门文章

最新文章