JavaWeb之Listener(监听器)

本文介绍了JavaWeb中的监听器组件,重点讲解了ServletContextListener的作用和实现方式。ServletContextListener监听ServletContext对象的创建和销毁,当web工程启动和停止时,会触发相应的回调方法。通过实现该接口并配置在web.xml中,可以在特定时刻执行初始化或销毁操作。
摘要由CSDN通过智能技术生成

一、什么是监听器、它有什么作用

listener监听器是javaWeb的三大组件之一。另外两大组件是servlet、filter。

listener是Java EE的规范,也就是接口

监听器的作用:

        监听某种事物的变化,然后回调函数,反馈给程序,做对应的处理。

二、ServletContextListener监听器及其实现方式

1.ServletContextListener:可以监听ServletContext对象的创建和销毁。

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

监听到创建和销毁时都会分别调用servletContextListener的两个方法。 

public interface ServletContextListener extends EventListener {

    //servletContext对象创建后调用
    default public void contextInitialized(ServletContextEvent sce) {}
    //servletContext对象销毁后调用
    default public void contextDestroyed(ServletContextEvent sce) {}
}

  2.实现方式:

(1)编写一个类实现servletContextListener;

(2)实现其两个回调方法;

(3)在web.xml中进行配置。

测试类:
public class MyServletListener 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.wq.listener.MyServletListener</listener-class> 
  </listener>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值