Listener 监听器

1、Listener 监听器

1.1、什么是 Listener 监听器

1、Listener 监听器它是 JavaWeb 的三大组件之一。JavaWeb 的三大组件分别是:Servlet 程序、Filter 过滤器、Listener 监听器。

2、Listener 它是 JavaEE 的规范,就是接口

3、监听器的作用是,监听某种事物的变化。然后通过回调函数,反馈给客户(程序)去做一些相应的处理。

1.2、ServletContextListener 监听器

ServletContextListener 它可以监听 ServletContext 对象的创建和销毁。

ServletContext 对象在 web 工程启动的时候创建,在 web 工程停止的时候销毁。

监听到创建和销毁之后都会分别调用 ServletContextListener 监听器的方法反馈。

两个方法分别是

public interface ServletContextListener extends EventListener {
	 /**
	 * 在 ServletContext 对象创建之后马上调用,做初始化 
	 **/ 
	 public void contextInitialized(ServletContextEvent sce); 
	
	/**
	* 在 ServletContext 对象销毁之后调用 
	*/ 
	public void contextDestroyed(ServletContextEvent sce); 

}

如何使用 ServletContextListener 监听器监听 ServletContext 对象。

使用步骤如下
1、编写一个类去实现 ServletContextListener
2、实现其两个回调方法
3、到 web.xml 中去配置监听器

监听器实现类

public class MyServletContextListenerImpl implements ServletContextListener { 
	@Override 
	public void contextInitialized(ServletContextEvent sce) { 
	
		System.out.println("ServletContext 对象被创建了"); 
	
	}
	
	@Override 
	public void contextDestroyed(ServletContextEvent sce) { 
		
		System.out.println("ServletContext 对象被销毁了"); 
	
	} 
}

web.xml 中的配置

<!--配置监听器--> 
<listener> 
<listener-class>com.tzm.listener.MyServletContextListenerImpl</listener-class> 
</listener>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

.诗酒趁年华

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值