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

DMSession

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);
  m_conn.setAutoCommit(false);
 
  session = new DMSession(request.getSession().getServletContext());
  request.getSession().setAttribute("session",session);
 }
 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.
DMSession.getInstance(request);

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");
   try
   {
    if (m_conn != null && !m_conn.isClosed())
      m_conn.close();
   }
   catch (SQLException e)
   {
    e.printStackTrace();
   }
   m_conn = null;
  }

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

IMPORTANT!!!

In your web.xml set:

  

   1


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