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 8. 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 8 apply to servlets. In our
example, we create a database connection within the servlet’s
init() method. Larger applications will
generally prefer to use a database connection pool, managed by the
servlet container. Connection pools and
DataSource objects (for container-managed
database connections) are discussed in Chapter 8. Another option would be
to use the object relational capabilities provided by Hibernate in
your servlet. Hibernate is discussed in Chapter 20.
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 database, where they can be easily
accessed. Now say you want to distribute these documents on the Web.
Luckily, servlets can dish out any form of content that can be defined
with a MIME header. All you have to do is set the appropriate content
type and use a
if you need to transmit binary data. Example ...