本文主要是介绍监听Web容器启动与关闭,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
在Servlet API 中有一个 ServletContextListener 接口,它能够监听 ServletContext 对象的生命周期,实际上就是监听 Web 应用的生命周期。
要监听web容器的启动与关闭,首先定义一个类继承ServletContextListener 接口:
package com;import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;public class TomcatListener implements ServletContextListener{/*** 监听web容器关闭*/@Overridepublic void contextDestroyed(ServletContextEvent sce) {System.out.println("web容器关闭");}/*** 监听web容器启动*/@Overridepublic void contextInitialized(ServletContextEvent sce) {System.out.println("web容器启动");}}
然后在web.xml中注册该类的监听器
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"><!-- 添加监听器 --><listener ><listener-class>com.TomcatListener</listener-class></listener><display-name></display-name> <welcome-file-list><welcome-file>index.jsp</welcome-file></welcome-file-list>
</web-app>
然后启动tomcat进行测试
这篇关于监听Web容器启动与关闭的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!