ITeye博客

怎样使用ServletContextListener接口

chenchh · 2010-05-19 16:13 · J2EE基础 · 编程语言 · Markdown

翻译自:http://www.iwebie.com/servletcontextlistener-interface

 

 

ServletContext : 每一个web应用都有一个 ServletContext与之相关联。 ServletContext对象在应用启动的被创建,在应用关闭的时候被销毁。 ServletContext在全局范围内有效,类似于应用中的一个全局变量。

 

ServletContextListener: 使用listener接口,开发者能够在为客户端请求提供服务之前向ServletContext中添加任意的对象。这个对象在ServletContext启动的时候被初始化,然后在ServletContext整个运行期间都是可见的。该接口拥有两个方法如下所示:

void contextDestoryd(ServletContextEvent sce);

void contextInitialized(ServletContextEvent sce);

 用户需要创建一个java类实现 javax.servlet.ServletContextListener接口并提供上面两个方法的实现。

 

 

示例: 当你需要在处理任何客户端请求之前创建一个数据库连接,并且希望在整个应用过程中该连接都是可用的,这个时候ServletContextListener接口就会十分有用了。

package com.database;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContextAttributesListener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import com.database.DbConnection;

public class DatabaseContextListener implements ServletContextListener {

  private ServletContext context = null;
  private Connection conn = null;

  public DatabaseContextListener() {

  }


  //该方法在ServletContext启动之后被调用,并准备好处理客户端请求
  public void contextInitialized(ServletContextEvent event)  {
    this.context = event.getServletContext();
    conn = DbConnection.getConnection;
    // 这里DbConnection是一个定制好的类用以创建一个数据库连接
    context = setAttribute(”dbConn”,conn);
  }

  //这个方法在ServletContext 将要关闭的时候调用
  public void contextDestroyed(ServletContextEvent event){
    this.context = null;
    this.conn = null; 
  }
}

 

然后部署该类,并在web.xml文件中添加

<listener>
com.database.DatabaseContextListener
</listener>

 一旦web应用启动的时候,我们就能在任意的servlet或者jsp中通过下面的方式获取数据库连接:

Connection conn = (Connection) getServletContext().getAttribute(”dbConn”);

评论(3)

  1. #3 楼 · TimePower · 2014-09-11 11:25

    chyzh2010 writes:

    listener在web.xml中你写错了。少了calss标签。

    对~哈哈~~

  2. #2 楼 · chyzh2010 · 2013-10-25 10:10

    listener在web.xml中你写错了。少了calss标签。

  3. #1 楼 · javatozhang · 2013-02-28 20:14

    讲的非常清晰,受用了! :D

评论功能维护中,当前仅展示历史评论。