web.xml加载顺序1

容器启动时,web.xml加载顺序:context-param --> listener --> filter --> servlet

  1. 启动容器时,容器读取项目的web.xml文件的 context-param 和 listener两个节点
  2. 容器创建上下文对象ServletContext,项目的所有部分都共享这个上下文对象
  3. 容器将<context-param>中的配置转换成key-value,提供给ServletContext
  4. 容器创建<listener>中的类实例,即创建监听      

对于上述第4点,创建的监听可以配置为框架中定义好的,也可以是自己写的类

比如:

package com.chaol.listener;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class BaseContextListener implements ServletContextListener {

	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		
		
	}

	@Override
	public void contextInitialized(ServletContextEvent arg0) {
		ServletContext context = arg0.getServletContext();
		String logPropertiesPath = context.getInitParameter("log4j");
		System.out.println("启动容器,创建监听");
		System.out.println(logPropertiesPath);
	}
	
}

web.xml中配置:

<context-param>
	<description>path of the logs</description>
	<param-name>log4j</param-name>
	<param-value>/WEB-INFO/logs</param-value>
</context-param>

<listener>
	<listener-class>com.chaol.listener.BaseContextListener</listener-class>
</listener>

启动Tomcat容器,输出内容:

.
.
九月 08, 2018 11:43:38 下午 org.apache.jasper.servlet.TldScanner scanJars
信息: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
启动容器,创建监听
/WEB-INFO/logs
九月 08, 2018 11:43:38 下午 org.apache.coyote.AbstractProtocol start
信息: Starting ProtocolHandler ["http-nio-8080"]
九月 08, 2018 11:43:38 下午 org.apache.coyote.AbstractProtocol start
信息: Starting ProtocolHandler ["ajp-nio-8009"]
九月 08, 2018 11:43:38 下午 org.apache.catalina.startup.Catalina start
信息: Server startup in 1910 ms

contextInitialized(ServletContextEvent arg0) 方法中,获取到上下文对象 ServletContext,读取web.xml中定义的属性,这个时候,项目还没有完全启动完全,一些需要在项目启动前初始化的连接或者数据,都可以定义在这里,比如建立数据库连接,获取数据库中的数据缓存。。

又比如加载Spring监听,这个是框架中已经存在的

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

由于listener的加载在filter之前,所以如果filter中要用到bean时,必须将spring的监听配置在web.xml中

对于监听器作用的理解:

扫描二维码关注公众号,回复: 3209839 查看本文章

    某些类 和 某些特定参数 配合使用,初始化一些资源,比如:

  •   ServletContextListener类 初始化上下文对象,如果有必要,还可以建立数据库连接等。。。
  •  Log4jConfigListener类  和配置在<context-param>中的log4gConfigLocation参数,初始化 log4j

猜你喜欢

转载自blog.csdn.net/ex_tang/article/details/82534449