Servlet Connection Strategies
From a programmer’s perspective, a servlet has three stages to its life cycle. They are defined by the following three methods, or types of methods:
-
init( ) This method is normally used to perform any initialization that should take place only once in the lifetime of the servlet. The
init( )method is invoked automatically before any of the servlet’sdoXXX( )methods can be called.-
doXXX( ) The various do methods --
doGet( ),doDelete( ),doPost( ), anddoPut( )-- are called as needed by web users to satisfy their dynamic content and form processing needs.-
destroy( ) This method is called just before the servlet container removes the servlet from memory, which typically happens when the servlet container itself is shutting down.
Given the life cycle described here, you have four strategies for making a database connection. The differences between these strategies hinge on when the connection is made and on whether connections are shared between servlets. The four strategies are:
- Per-transaction connection
You load the Oracle JDBC driver in the servlet’s
init( )method, open a connection at the beginning of eachdoXXX( )method, and close that connection at the end of eachdoXXX( )method.- Dedicated connection
You use a combination of the
init( )anddestroy( )methods, whereby you load the driver and open a connection in theinit( )method, and then close that connection in thedestroy( )method. As a result, the servlet uses one connection that remains ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access