Skip to Main Content
Java Servlet Programming
book

Java Servlet Programming

by Jason Hunter
November 1998
Intermediate to advanced content levelIntermediate to advanced
526 pages
14h 38m
English
O'Reilly Media, Inc.
Content preview from Java Servlet Programming

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 ...
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.
Start your free trial

You might also like

Java Servlet Programming, 2nd Edition

Java Servlet Programming, 2nd Edition

Jason Hunter, William Crawford

Publisher Resources

ISBN: 156592391XSupplemental ContentCatalog PageErrata