ServletContextListener 详解

1.首先来看一看源码 该类的源码

public interface ServletContextListener extends EventListener {

    /**
     * Receives notification that the web application initialization
     * process is starting.
     *
     * <p>All ServletContextListeners are notified of context
     * initialization before any filters or servlets in the web
     * application are initialized.
     *
     * @param sce the ServletContextEvent containing the ServletContext
     * that is being initialized
     */
    public void contextInitialized(ServletContextEvent sce);

    /**
     * Receives notification that the ServletContext is about to be
     * shut down.
     *
     * <p>All servlets and filters will have been destroyed before any
     * ServletContextListeners are notified of context
     * destruction.
     *
     * @param sce the ServletContextEvent containing the ServletContext
     * that is being destroyed
     */
    public void contextDestroyed(ServletContextEvent sce);
}

此接口中提供了两个方法,用于监听ServletContext  的创建和销毁,也就是监听ServletContext 的生命周期,可以说成是监听Web 应用的生命周期,当web应用启动后,就会触发ServletContextEvent 事件 当此事件执行时,就会被ServletContextListener 监听器监听到,会调用他的 contextInitialized(ServletContextEvent sce)  方法,通过sce 可以获取ServletContext 实例,初始化一些数据,例如缓存的应用,如,创建数据库连接,读取数据库数据,通过setAttribute(“”,obj) 方法设置数据,然后就是可通过servlet 获取servletContext 的实例,通过getAttribute("") 获取设置的数据

实现代码:

public class MyContextListener implements ServletContextListener {
	private ServletContext context = null;

	public void contextInitialized(ServletContextEvent event) {
		context = event.getServletContext();
		User user = DatabaseManager.getUserById(1);
		context.setAttribute("user1", user);
	}
 
	public void contextDestroyed(ServletContextEvent event) {
		User user = (User)context.getAttribute("user1");
		DatabaseManager.updateUserData(user);
		this.context = null;
	}
}

如果是web 项目 最后一步是使 ServletContext 生效,需要在web.xml 中配置监听器,并且web.xml  把它放在正确的WEB-INF/classes目录下,

<listener>
	<listener-class>MyServletContextListener</listener-class>
</listener>







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值