天天看点

JavaWeb初识监听器

文章目录

  • ​​简要说明​​
  • ​​ServletContextListener 监听器​​
  • ​​如何使用​​
  • ​​简单示例​​
  • ​​监听器配置​​
  • ​​Web.xml配置​​

简要说明

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

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

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

ServletContextListener 监听器

现在常用的监听器便是ServletContextListener 监听器,它可以监听ServletContext 对象的创建和销毁。

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

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

如何使用

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

简单示例

监听器配置

public class MyServletContextListener implements ServletContextListener,
        HttpSessionListener, HttpSessionAttributeListener {

    // Public constructor is required by servlet spec
    public MyServletContextListener() {
    }

    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("监听器启动");
    }

    public void contextDestroyed(ServletContextEvent sce) {
      /* This method is invoked when the Servlet Context 
         (the Web application) is undeployed or 
         Application Server shuts down.
      */
        System.out.println("监听器销毁");
    }
}      

Web.xml配置

<listener>
        <listener-class>com.stackery.listener.MyServletContextListener</listener-class>
</listener>