The EAServer implementation of application life cycle events enables you to register event listeners that can respond to state changes in a Web application’s ServletContext and HttpSession objects. When a Web application starts up, EAServer instantiates the listeners that are declared in the deployment descriptor. See “Event Types and Listener Interfaces” in the Java Servlet 2.4 specification for a description of the listener interfaces, which EAServer calls when each event occurs.
Here is an example of how a ServletContextListener can be used to maintain a database connection for each servlet context. The database connection that is created is stored in the ServletContext object as an attribute, so it is available to all the servlets in the Web application.
package listeners; import javax.servlet.*; import java.sql.*; public final class ContextListener implements ServletContextListener { ServletContext _context = null; Connection _connection = null; /** * This method gets invoked when the ServletContext has * been destroyed. It cleans up the database connection. */ public void contextDestroyed(ServletContextEvent event) { // Destroy the database connection for this context. _context.setAttribute("DBConnection", null); _context = null; try { _connection.close(); } catch (SQLException e) { // ignore the exception } } /** * This method is invoked after the ServletContext has * been created. It creates a database connection. */ public void contextInitialized(ServletContextEvent event) { _context = event.getServletContext(); String jdbcDriver="com.sybase.jdbc2.jdbc.SybDriver"; String dbURL="jdbc:sybase:Tds:localhost:2638"; String user="dba"; String password=""; try { // Create a connection and store it in the ServletContext // as an attribute of type Connection. Class.forName(jdbcDriver).newInstance(); Connection conn = DriverManager.getConnection(dbURL,user,password); _connection = conn; _context.setAttribute("DBConnection", conn); } catch (Exception e) { // Unable to create the connection, set it to null. _connection = null; _context.setAttribute("DBConnection", null); } } }