文章目录
Listener概述
Listener 表示监听器,是 JavaWeb 三大组件(Servlet、Filter、Listener)之一。
监听器可以监听就是在 application
,session
,request
三个对象创建、销毁或者往其中添加修改删除属性时自动执行代码的功能组件。
request 和 session 我们已经了解。而 application
是 ServletContext
类型的对象。
ServletContext
代表整个web应用,在服务器启动的时候,tomcat会自动创建该对象。在服务器关闭时会自动销毁该对象。
JavaWeb 提供了8个监听器:
监听器分类 | 监听器名称 | 作用 |
---|---|---|
ServletContext监听 | ServletContextListener | 用于对ServletContext对象进行监听(创建、销毁) |
– | ServletContextAttributeListener | 对ServletContext对象中属性的监听(增删改属性) |
Session监听 | HttpSessionListener | 对Session对象的整体状态的监听(创建、销毁) |
– | HttpSessionAttributeListener | 对Session对象中的属性监听(增删改属性) |
– | HttpSessionBindingListener | 监听对象于Session的绑定和解除 |
– | HttpSessionActivationListener | 对Session数据的钝化和活化的监听 |
Request监听 | ServletRequestListener | 对Ruquest对象进行监听(创建、销毁) |
– | ServletRequestAttributeListener | 对Ruquest对象中属性的监听(增删改属性) |
基本使用
这里面只有 ServletContextListener
这个监听器后期我们会接触到,ServletContextListener
是用来监听 ServletContext
对象的创建和销毁。
ServletContextListener
接口中有以下两个方法
void contextInitialized(ServletContextEvent sce)
:ServletContext
对象被创建了会自动执行的方法void contextDestroyed(ServletContextEvent sce)
:ServletContext
对象被销毁时会自动执行的方法
代码实现
接下来我们就以 ServletContextListener
这个监听器为例子:
@WebListener()
public class ListenerDemo1 implements ServletContextListener {
// -------------------------------------------------------
// ServletContextListener implementation
// -------------------------------------------------------
public void contextInitialized(ServletContextEvent sce) {
/* This method is called when the servlet context is
initialized(when the Web application is deployed).
You can initialize servlet context related data here.
*/
//加载资源
System.out.println("ContextLoaderListener...");
}
public void contextDestroyed(ServletContextEvent sce) {
/* This method is invoked when the Servlet Context
(the Web application) is undeployed or
Application Server shuts down.
*/
//释放资源
}
}
启动服务器,就可以在启动的日志信息中看到 contextInitialized()
方法输出的内容,同时也说明了 ServletContext
对象在服务器启动的时候被创建了。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/122101.html