A Database Servlet

This chapter has covered a lot of ground. Now it is time to put all the information together in a single, concrete example: a Java servlet that serves up dynamic HTML content based on data in a database. This servlet will serve as a simple guest book. Visitors to the web page can enter their name, email address, and a few comments, as well as view a random list of other visitors to the site. This example assumes some level of familiarity with Java servlets, but you do not really need to have servlet knowledge to pick out the bits relevant to database access. For an excellent discussion of the Java Servlets API, see Java Servlet Programming by Jason Hunter with William Crawford (O’Reilly).

Getting Configuration Information

Before you can connect to a database, you need to have the information to make the connection. As the examples in this chapter have shown, and Example 3.2 in particular, you need a JDBC URL, the proper connection properties, and a way to register one or more JDBC drivers. For a servlet, the place to get this information is in the init( ) method. Like init() in applets, it is where a servlet does its initialization. It accepts the ServletConfig instance for this servlet from which you can grab initialization parameters. For this example, I have prefixed all initialization parameters with “gb.”:

public void init(ServletConfig cfg) throws ServletException { super.init(cfg); driverName = cfg.getInitParameter("gb.driver"); jdbcURL = cfg.getInitParameter("gb.jdbcURL"); ...

Get Database Programming with JDBC & Java, 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.