web程序的初始化问题——ServletContextListener----调试成功

来源:互联网 发布:vscode c 生成exe 编辑:程序博客网 时间:2024/05/01 23:15
原文:http://wanchuyang.blogbus.com/logs/2005/01/566411.html  
web程序的初始化问题——ServletContextListener
时间: 2005-01-04

应用ServletContextListener接口,可以实现在web应用程序初始化时,自动运行一些初始化程序。

ServletContextListener接口定义的方法

方法名称

调用时机

Void contextInitialized(ServletContextEvent sce)

Web应用程序的“初始阶段”,Servlet容器会调用ServletContextListener对象的contextInitialized()方法

Void contextDestroyed(ServletContextEvent sce)

Web应用程序的“结束阶段”,Servlet容器会调用ServletContextListener对象的contextDestoryed()方法

应用此接口时,要在web.xml文件内定义“监听器类”的名称,此时要注意:

在Servlet规范中并未限制一个Web应用程序只能对应一个“监听器类”,但是在web.xml内定义<listener>元素时得注意下列两点:
<listener>元素必须出现在任何Context起始参数(由<context-param>元素所定义)之后。
<listener>元素必须出现在任何Servlet实体(由<servlet>元素所定义)之前。

举例:

web.xml:

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

<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee web-app_2_4.xsd"
    version="2.4">

    <description>
      test servlet listener
    </description>
    <display-name>testServletListener</display-name>
 <listener>
  <listener-class>com.chuyang.Test
   </listener-class>
</listener>
 
</web-app>

Test.java:

package com.chuyang;

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

public class Test implements ServletContextListener {
 public void contextInitialized(ServletContextEvent event) {
  System.out.println("servlet initialized.........");
 }
 public void contextDestroyed(ServletContextEvent event) {
  System.out.println("servlet destroyed..........");
 }
}
原创粉丝点击