Skip to main content

Database Connection Created with a New Session Using this Servlet Code.

With DeployHub, database connections must be established with a new browser session. This can be tricky on both opening and closing connections. Our servlet code creates a new database connection when a new session is created. This database connection is part of our DMSession object as a private variable m_conn.
database connection per browser session


The DMSession object is stored against the session as follows:

public static DMSession getInstance(HttpServletRequest request)
 DMSession session = null;

 if ((session=(DMSession)request.getSession().getAttribute("session")) == null)
  m_conn = DriverManager.getConnection(ConnectionString,dUserName,dPassword);
  session = new DMSession(request.getSession().getServletContext());
 return session;

Using the getInstance we ensure that we only create one instance of DMSession object per session and one database connection per session. Therefore, each servlet that needs to interact with the database just calls the static method to get connected.

Consequently, controlling when you connect to the DB is easy since a new session is being established. However, what happens when the user closes their browser?  First of all, the servlet container, Tomcat, Jetty, etc. still has an open connection to the DB. The result, eventually you will run out of available database connections that the DB server can offer up.  Therefore, closing the DB connections is a must to avoid this issue. How? Implement HttpSessionBindingListener interface to provide the hooks. ValueBound, valueUnbound. valueUnbound is called anytime the servlet container does its cleanup for a session.
public void valueUnbound(HttpSessionBindingEvent arg0)
   System.out.println("UNBOUND SESSION");
    if (m_conn != null && !m_conn.isClosed())
   catch (SQLException e)
   m_conn = null;

In our valueUnbound we check to see if the connection has been established or not and close it appropriately.


In your web.xml set:



This value is in minutes. We set it to 1 minute for testing. Production we will be setting it to 1 hour.