Servlet Context Listener Database Connection Pool

Load a Database Connection Pool into the Servlet Context so that it can be used across any servlet.

Javadoc available at https://www.javatapas.com/docs/javatapas/servlet/ServletContextListenerDbPool.html


	ServletContext servletContext;

	public void contextInitialized(ServletContextEvent contextEvent) {

		System.out.println("Context Created");
		servletContext = contextEvent.getServletContext();

		DataSource datasource = null;

		System.out.println("Establishing Reference to Connection Pool");

		try {
			Context initContext = new InitialContext();
			Context envContext  = (Context)initContext.lookup("java:/comp/env");
			datasource = (DataSource)envContext.lookup("jdbc/DbConnPool");  // this must be set in your container conf file within the context tag.
		}

		catch(NamingException ex){ex.printStackTrace();}

		servletContext.setAttribute("dbPool", datasource);

	}

	public void contextDestroyed(ServletContextEvent contextEvent) {

		ServletContext contextDestroy = contextEvent.getServletContext();
		if (!servletContext.equals(contextDestroy)){
			System.out.println("New Context Found Upon Destroying");
		}

    System.out.println("Context Destroyed");

  }

}