---
title: "servlet listener"
author: "speed847"
date: "2013-09-03T03:43:42Z"
tags: []
categories: ["移动开发"]
slug: "servlet-listener"
draft: false
lastmod: "2013-09-03T03:43:42Z"
id: 1935696
url: "https://speed847.iteye.com/blog/1935696"
---

[http://sakyone.iteye.com/blog/471093](http://sakyone.iteye.com/blog/471093)

Listener的作用类似于load-on-startup的Servlet,在Web应用启动时被加载,在Web应用关闭时被销毁，Listener用来作为Web应用的后台服务，比load-on-startup的Servlet更早被加载到Servlet容器中。自定义的Listener类必须实现ServletContextListener接口，并实现该接口的两个方法：contextInitialized(ServletContextEvent)和contextDestroyed(ServletContextEvent)，例如：

public class GetConnListener implements ServletContextListener{  
 public void contextInitialized(ServletContextEvent sce){  
  try{  
   ServletContext application=sce.getServletContext();  
   String driver=application.getInitParameter("driver");  
   String url=application.getInitParameter("url");  
   String user=application.getInitParameter("user");  
   String password=application.getInitParameter("password");  
   Class.forName(driver);  
   Connection conn=DriverManager.getConnection(url, user, password);  
   application.setAttribute("conn", conn);  
  }catch(Exception e){  
   System.out.println("Listener中获取数据库连接出现异常:"+e.getMessage());  
  }  
 }  
 public void contextDestroyed(ServletContextEvent sce){  
  ServletContext application=sce.getServletContext();  
  Connection conn=(Connection)application.getAtrribute("conn");  
  if(conn!=null){  
   try{  
    conn.close();  
    conn=null;  
   }catch(Exception e){}  
  }  
 }  
}

Listener配置：

&lt;listener&gt;

  &lt;listener-class&gt;lee.GetConnListener&lt;/listener-class&gt;

&lt;/listener&gt;