JavaWeb初识监听器

简要说明

1、Listener 监听器它是 JavaWeb 的三大组件Servlet 程序、Filter 过滤器、Listener监听器之一。
2、Listener 它是 JavaEE 的规范,就是接口。
3、监听器的作用是,监听某种事物的变化。然后通过回调函数,反馈给客户(程序)去做一些相应的处理。

ServletContextListener 监听器

现在常用的监听器便是ServletContextListener 监听器,它可以监听ServletContext 对象的创建和销毁。
ServletContext 对象在 web 工程启动的时候创建,在 web 工程停止的时候销毁。
监听到创建和销毁之后都会分别调用 ServletContextListener 监听器的方法反馈。

如何使用

如何使用 ServletContextListener 监听器监听 ServletContext 对象
使用步骤如下:

  • 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配置

这个比Servlet简单很多

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

猜你喜欢

转载自blog.csdn.net/solitudi/article/details/107253341