Databases and Non-HTML Content

Most web applications need to communicate with a database, either to generate dynamic content or collect and store data from users, or both. With servlets, this communication is easily handled using the JDBC API described in Chapter 2. Thanks to JDBC and the generally sensible design of the servlet lifecycle, servlets are an excellent intermediary between a database and web clients.

Most of the general JDBC principles discussed in Chapter 2 apply to servlets. However, servlet developers should keep a few things in mind for optimal performance. First, JDBC Connection objects can be created in the servlet’s init( ) method. This allows the servlet to avoid reconnecting to the database (a la CGI) with each request, saving up to a second or more on every single page request. If you anticipate high volume, you may want to create several connections and rotate between them. An excellent freeware connection-pooling system is available at http://www.javaexchange.com. Or, if you’re using JDBC 2.0, the javax.sql package provides a connection-pooling mechanism. Finally, if you plan on using JDBC’s transaction support, you need to create individual connections for each request or obtain exclusive use of a pooled connection.

So far, all our servlets have produced standard HTML content. Of course, this is all most servlets ever do, but it’s not all that they can do. Say, for instance, that your company stores a large database of PDF documents within an Oracle ...

Get Java Enterprise in a Nutshell, Second Edition 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.