使用Spring MVC如何启动初始化

发布时间:2020-11-26 16:50:59 作者:Leah
来源:亿速云 阅读:184

今天就跟大家聊聊有关使用Spring MVC如何启动初始化,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

Web容器初始化过程

web容器初始化的过程,其官方文档给出了这样的描述:

  1. Instantiate an instance of each event listener identified by a <listener> element in the deployment descriptor.For instantiated listener instances that implement ServletContextListener, call the contextInitialized() method.

  2. Instantiate an instance of each filter identified by a <filter> element in the deployment descriptor and call each filter instance's init() method.

  3. Instantiate an instance of each servlet identified by a <servlet> element that includes a <load-on-startup> element in the order defined by the load-on-startup element values, and call each servlet instance's init() method.

其初始化的过程实际如下:

使用Spring MVC如何启动初始化

SpringMVC 的 web.xml配置

web.xml 配置代码:

<?xml version="1.0" encoding="UTF-8"?> 
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" 
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
   xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> 
 
 <context-param> 
  <param-name>contextConfigLocation</param-name> 
  <param-value>classpath:applicationContext.xml</param-value> 
 </context-param> 
 
 <listener> 
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 
 </listener> 
 
 
 <servlet> 
  <servlet-name>mvc-dispatcher</servlet-name> 
  <servlet-class> 
   org.springframework.web.servlet.DispatcherServlet 
  </servlet-class> 
  <load-on-startup>1</load-on-startup> 
 </servlet> 
                                   
 <servlet-mapping> 
  <servlet-name>mvc-dispatcher</servlet-name> 
  <url-pattern>/</url-pattern> 
 </servlet-mapping> 
 
</web-app>

在 Servlet API中有一个ServletContextListener接口,它能够监听ServletContext对象的生命周期,实际上就是监听Web应用的生命周期。当Servlet容器启动或终止Web应用时,会触发ServletContextEvent事件,该事件由ServletContextListener来处理。在ServletContextListener接口中定义了处理ServletContextEvent 事件的两个方法contextInitialized()contextDestroyed()

ContextLoaderListener监听器的作用就是启动Web容器时,自动装配ApplicationContext的配置信息。因为它实现了ServletContextListener这个接口,在web.xml配置了这个监听器,启动容器时,就会默认执行它实现的方法。由于在ContextLoaderListener中关联了ContextLoader这个类,所以整个加载配置过程由ContextLoader来完成。

DispatchServlet初始化

在SpringMVC架构中,DispatchServlet负责请求分发,起到控制器的作用。下面详细来解释说明:

使用Spring MVC如何启动初始化

DispatchServlet类和ContextLoaderListener类的关系图:

使用Spring MVC如何启动初始化

用ContextLoaderListener初始化上下文,接着使用DispatchServlet来初始化WebMVC的上下文

看完上述内容,你们对使用Spring MVC如何启动初始化有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。

推荐阅读:
  1. Spring MVC 快速入门-01
  2. 深入分析Spring 与 Spring MVC容器

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

springmvc

上一篇:怎么利用ViewPager实现一个翻页效果

下一篇:如何在android应用中利用ViewPager与Fragment实现无限滑动功能

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》