Web项目初始化流程

本文只讨论使用web.xml配置文件启动web容器的方式

Web服务器启动时,部署在web容器上的项目即开始初始化

初始化流程如下:

                         1.Web容器首先读取项目中web.xml配置文件中的两个节点:<context-param><listener>节点并完成初始化

                         2.Web容器创建ServletContext对象即Servlet上下文,ServletContext代表整个Web应用,是Servlet的共享区

                         3.Web容器将<context-param>转换为键值对,并交给ServletContext

                         4.执行Listener(这里拿ServletContextListener为例),ServletContextListener接口有两个方法:contextinitialized()、contextDestroyed(),用来监听ServletContext对象的创建与销毁,当监测到ServletContext对象创建时,调用contextInitialized()方法,将ServletContext对象封装到方法的事件对象中:在contextInitialized()方法内部代码如下:

/*通过事件对象获取封装的servletContext对象*/
servletContext=ServletContextEvent.getServletContext();
/*通过键值获得context-param的值*/
Context-param=ServletContext.getInitParameter("context-param的键");

                         5.获得context-param并进行相关操作,例如在项目启动的时候创建数据库等在项目初始化时需要进行的操作

                         6.加载filter

                         7.Web容器读取每个Servlet设置信息,并生成代表对象servletconfig,此时将servletcontext设置在servletconfig中,可以从servletconfig中获取到servletcontext对象来获取上下文信息,实例化servlet在web容器中,收到请求后,servlet开始服务,传入servletconfig到servlet的init方法中进行servlet初始化(这个过程只进行一次)即servlet在web容器启动的时候即已完成实例化,并且在处理http请求的时候才进行初始化

               综上:web.xml配置文件中的节点加载顺序为:

                                context-param->listener->filter->servlet

 

猜你喜欢

转载自blog.csdn.net/weixin_38753309/article/details/84523920