Reusing Database Objects

In the introduction, we mentioned that the servlet life cycle allows for extremely fast database access. After you’ve used JDBC for a short time, it will become evident that the major performance bottleneck often comes right at the beginning, when you are opening a database connection. This is rarely a problem for most applications and applets because they can afford a few seconds to create a Connection that is used for the life of the program. With servlets this bottleneck is more serious because we are creating and tearing down a new Connection for every page request. Luckily, the servlet life cycle allows us to reuse the same connection for multiple requests, even concurrent requests, as Connection objects are required to be thread safe.

Reusing Database Connections

A servlet can create one or more Connection objects in its init() method and reuse them in its service(), doGet(), and doPost() methods. To demonstrate, Example 9.4 shows the phone lookup servlet rewritten to create its Connection object in advance. It also uses the HtmlSQLResult class from Example 9.3 to display the results. Note that this servlet uses the Sybase JDBC driver.

Example 9-4. An improved directory servlet

import java.io.*; import java.sql.*; import javax.servlet.*; import javax.servlet.http.*; public class DBPhoneLookupReuse extends HttpServlet { private Connection con = null; public void init(ServletConfig config) throws ServletException { super.init(config); try { // Load (and ...

Get Java Servlet Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.