A Guest Book Servlet

You have probably heard quite a bit of talk about Java applets. We discussed in Chapter 8, however, how doing database access in the client is a really bad idea. We have packaged with the examples in this book an example that contains a real application that uses the JDBC knowledge we have discussed in this chapter to create a server-side Java class known as a servlet. While servlets are not in themselves part of the three-tier solution we discussed in Chapter 8, this example should provide a useful example of how JDBC can be used. The servlet in question is a web page that lets people visiting your site enter comments about it. Others can then view these comments. For this example, all you need to know about servlets is that the doPost() method handles HTTP POST events and doGet() handles HTTP GET events.

There are two pieces to this servlet: the get and the post. In both pieces, a call is made to printComments() to show the comments in the guest book. In this method, we encounter something we have not yet seen in the previous simple examples, a call to wasNull() after each column value is retrieved. As its name implies, wasNull() returns true if the last value fetched was SQL NULL. For calls returning a Java object, the value will generally be NULL when a SQL NULL is read from the database. In these instances, wasNull() may appear somewhat redundant. For primitive datatypes, however, a valid value may be returned on a fetch. The wasNull() method gives you ...

Get MySQL and mSQL 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.