---
title: "web程序的初始化问题——ServletContextListener----调试成功"
author: "fuyangchang"
date: "2007-07-09T11:08:00Z"
tags: []
slug: "web-servletcontextlistener"
draft: false
lastmod: "2007-07-09T11:08:00Z"
id: 104056
url: "https://csdn.iteye.com/blog/104056"
---

原文:[http://wanchuyang.blogbus.com/logs/2005/01/566411.html](http://wanchuyang.blogbus.com/logs/2005/01/566411.html%C2%A0%C2%A0)  

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内定义&lt;listener&gt;元素时得注意下列两点：  
&lt;listener&gt;元素必须出现在任何Context起始参数（由&lt;context-param&gt;元素所定义）之后。  
&lt;listener&gt;元素必须出现在任何Servlet实体（由&lt;servlet&gt;元素所定义）之前。

举例：

web.xml:

&lt;?xml version="1.0" encoding="ISO-8859-1"?&gt;

&lt;web-app xmlns="[http://java.sun.com/xml/ns/j2ee](http://java.sun.com/xml/ns/j2ee)"  
    xmlns:xsi="[http://www.w3.org/2001/XMLSchema-instance](http://www.w3.org/2001/XMLSchema-instance)"  
    xsi:schemaLocation="[http://java.sun.com/xml/ns/j2ee](http://java.sun.com/xml/ns/j2ee) web-app\_2\_4.xsd"  
    version="2.4"&gt;

    &lt;description&gt;  
      test servlet listener  
    &lt;/description&gt;  
    &lt;display-name&gt;testServletListener&lt;/display-name&gt;  
 &lt;listener&gt;  
  &lt;listener-class&gt;com.chuyang.Test  
   &lt;/listener-class&gt;  
&lt;/listener&gt;  
   
&lt;/web-app&gt;

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..........");  
 }  
}