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 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 ServletOuputStream if you need to transmit binary data. Example ...

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