Listener

举报
十八岁讨厌编程 发表于 2022/08/06 00:47:15 2022/08/06
【摘要】 文章目录 Listener概述基本使用代码实现 Listener概述 Listener 表示监听器,是 JavaWeb 三大组件(Servlet、Filter、Listener)之一。 ...

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.
      */
        //释放资源
    }
}

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

启动服务器,就可以在启动的日志信息中看到 contextInitialized() 方法输出的内容,同时也说明了 ServletContext 对象在服务器启动的时候被创建了。
在这里插入图片描述

文章来源: blog.csdn.net,作者:十八岁讨厌编程,版权归原作者所有,如需转载,请联系作者。

原文链接:blog.csdn.net/zyb18507175502/article/details/125669869

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0)

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。