Java Web学习 Listener

1 概述

(1) Listener 表示监听器,是JavaWeb三大组件(Servlet、Filter、Listener)之一。
(2) 监听器可以监听就是在 application,session,request 三个对象创建、销毁或者往其中添加修改删除属性时自动执行代码的功能组件。
(3) application 是ServletContext类型的对象。ServletContext代表整个web应用,在服务器启动的时候,tomcat会自动创建该对象。在服务器关闭时会自动销毁该对象。


2 分类

(1) JavaWeb 提供了8个监听器
<1> Servletcontext监听
ServletContextListener:用于对Servletcontext对象进行监听(创建、销毁)
ServletContextAttributelistener:对Servletcontext对象中属性的监听(增删改属性)
<2> Session监听
HttpsessionListener:对session对象的整体状态的监听(创建、销毁)
HttpSessionAttributeListener:对Session对象中的属性监听(增删改属性)
HttpsessionBindinglistener:监听对象于Session的绑定和解除
HttpsessionActivationListener:对Session数据的纯化和活化的监听
<3> Request监听
ServletRequestListener:对Request对象进行监听(创建、销毁)
ServletRequestattributeListener:对Request对象中属性的监听(增删改属性)
(2) 这里面只有 ServletContextListener 这个监听器后期我们会接触到, ServletContextListener 是用来监听ServletContext 对象的创建和销毁。
(3) ServletContextListener 接口中有以下两个方法
<1> void contextInitialized(ServletContextEvent sce) : ServletContext 对象被创建了会自动执行的方法
<2> void contextDestroyed(ServletContextEvent sce) : ServletContext 对象被销毁时会自动执行的方法

 

3 代码实现

(1) 定义一个类,实现 ServletContextListener 接口

public class ContextLoaderListener implements ServletContextListener {
}

(2) 重写所有的抽象方法

public class ContextLoaderListener implements ServletContextListener {
	@Override
	public void contextInitialized(ServletContextEvent sce) {
		//加载资源
	}
	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		//释放资源
	}
}

(3) 使用 @WebListener 进行配置

@WebListener
public class ContextLoaderListener implements ServletContextListener {
	@Override
	public void contextInitialized(ServletContextEvent sce) {
		//加载资源
	}
	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		//释放资源
	}
}

 

posted @ 2023-03-28 11:31  10kcheung  阅读(40)  评论(0)    收藏  举报