All you need to do is write a java class that implements the ServletContextListener interface. This class must implement two method contextInitialized method which is called when the web application is first created and contextDestroyed which will get called when it is destroyed. The resource that you want to be initialized would be instantiated in the contextInitialized method and the resource freed up in the contextDestroyed class. The application must be configured to call this class when it is deployed which is done in the web.xml descriptor file.
public class ServletContextClass implements ServletContextListener
{
public static Connection con;
public void contextInitialized(ServletContextEvent arg0)
{
con.getInstance ();
}//end contextInitialized method
public void contextDestroyed(ServletContextEvent arg0)
{
con.close ();
}//end constextDestroyed method
}
The web.xml configuration
<listener>
<listener-class>com.nameofpackage.ServletContextClass</listener-class>
</listener>
This now will let the application call the ServletContextClass when the application is deployed and instantiate the Connection or any other resource place in the contextInitialized method some what similar to what the Servlet init method does.