Tomcat指定应用事件监听

来源:互联网 发布:java 常量 编辑:程序博客网 时间:2024/04/26 11:57



在tomcat中,监听各类消息:如tomcat启动、关闭等

[@more@]

Tomcat指定应用事件监听

应用事件监听器程序是建立或修改servlet环境或会话对象时通知的类。它们是servlet规范的版本2.3中的新内容。这里只简单地说明用来向Web应用注册一个监听程序的web.xml的用法。

注册一个监听程序涉及在web.xmlweb-app元素内放置一个listener元素。在listener元素内,listener-class元素列出监听程序的完整的限定类名,如下所示:

<listener>

<listener-class>package.ListenerClass</listener-class>

</listener>

虽然listener元素的结构很简单,但请不要忘记,必须正确地给出web-app元素内的子元素的次序。listener元素位于所有的servlet元素之前以及所有filter-mapping元素之后。此外,因为应用生存期监听程序是serlvet规范的2.3版本中的新内容,所以必须使用web.xml DTD2.3版本,而不是2.2版本。

例如,程序清单5-20给出一个名为ContextReporter的简单的监听程序,只要Web应用的Servlet-Context建立(如装载Web应用)或消除(如服务器关闭)时,它就在标准输出上显示一条消息。程序清单5-21给出此监听程序注册所需要的web.xml文件的一部分。

程序清单ContextReporterjava

package moreservlets;

import javax.servlet.*;

import java.util.*;

/** Simple listener that prints a report on the standard output

* when the ServletContext is created or destroyed.

* <P>

* Taken from More Servlets and JavaServer Pages

* from Prentice Hall and Sun Microsystems Press,

* http://www.moreservlets.com/.

* &copy; 2002 Marty Hall; may be freely used or adapted.

*/

public class ContextReporter implements ServletContextListener {

public void contextInitialized(ServletContextEvent event) {

System.out.println("Context created on " +

new Date() + ".");

}

public void contextDestroyed(ServletContextEvent event) {

System.out.println("Context destroyed on " +

new Date() + ".");

}

}

程序清单 web.xml(声明一个监听程序的摘录)

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app

PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"

"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

<!-- ... -->

<filter-mapping> … </filter-mapping>

<listener>

<listener-class>package.ListenerClass</listener-class>

</listener>

<servlet> ... </servlet>

<!-- ... -->

</web-app>

参考资料:

http://blog.csdn.net/feng_sundy/archive/2006/04/24/675320.aspx14

0 0
原创粉丝点击