通过implements ServletContextListener实现监听器Linstener

package cn.config;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

/*
* Servlet 容器启动或终止Web 应用时,会触发ServletContextEvent事件
* 
* ServletContext对象是一个为整个Web应用提供共享的内存,任何请求都可以获取里面的内容
* 实现ServletContextListener时通过ServletContext.setAttribute(key,value)将内容提交到内存中
* 其他地方通过ServletContext.getAttribute(key)获取内容(HelloWorld#doPost)
* 
* 官方对于ServletContextEvent的介绍:
* This is the event class for notifications about changes to the servlet context of a web application.
*/

public class MyLinstener implements ServletContextListener {

    /**
     * ① Servlet启动时先调用contextInitialized方法, 之后再对Filter和需要被初始化的Servlet初始化
     */
    @Override
    public void contextInitialized(ServletContextEvent paramServletContextEvent) {
        ServletContext context = paramServletContextEvent.getServletContext();
        context.setAttribute("linstener", "fromContextInitialized");
        System.out.println("...    contextInitialized    ... ");
    }

    /**
     * ② Servlet停止时先销毁所有的Servlet和Filter, 再调用contextDestroyed方法
     */
    @Override
    public void contextDestroyed(ServletContextEvent paramServletContextEvent) {
        ServletContext dest = paramServletContextEvent.getServletContext();
        System.out.println("contextDestroyed... " + dest.getAttribute("linstener"));
    }

}

web.xml配置监听器

<listener>
    <listener-class>cn.config.MyLinstener</listener-class>
</listener>

控制台输出

①. 启动web服务器的时候会打印... contextInitialized ...
②. 停止服务器的时候会打印contextDestroyed... fromContextInitialized,fromContextInitialized是Server启动时通过context.setAttribute("linstener", "fromContextInitialized")添加到ServletContext中的.

标签: 监听器, servlet, listener

添加新评论