Server-Side Java with Jakarta-Tomcat

Simple ways to build web applications using servlets.
A Simple Set of Servlets

To demonstrate how easy it is to write servlets, we will create a simple web application—a blog-creation tool. Blogs, or “web logs”, are increasingly popular web diaries in which the newest entries traditionally appear at the top. The first web log was Dave Winer's Scripting News (, but there are many thousands of web logs that provide useful news and commentary on a variety of topics.

We will use servlets to create a very simple web log. The actual log entries will be stored in a PostgreSQL database, which we can define as follows:

CREATE TABLE BlogEntries (
  entry_id       SERIAL    NOT NULL  PRIMARY KEY,
  entry_date     DATETIME  NOT NULL  CHECK

  entry_headline TEXT      NOT NULL  CHECK

  entry_text     TEXT      NOT NULL  CHECK

  UNIQUE(entry_date, entry_headline)

Since we're going to be retrieving data by date and headline, we create an index on each of two columns:

CREATE INDEX headline_date_index ON BlogEntries

CREATE INDEX entry_headline_index ON BlogEntries (entry_headline);
Now that we have created our database table and indices, we will need to create two servlets: one servlet will receive input from an HTML form and use that input to insert a new row into the BlogEntries table. (Presumably, this servlet will only be available to the owner of the site, who is the editor of the web log.) The second servlet will retrieve all web log entries from the last three days, displaying them in the traditional last-in-first-printed order.

The servlet for adding a new web log entry, AddBlogEntry [see Listing 3 at], expects to receive two parameters from an HTML form. The first parameter (entry_headline) contains the headline, while the second (entry_text) contains the text associated with it.

The servlet in Listing 3 defines an instance variable con which contains the JDBC database connection. The servlet also defines three methods:

  • init, which is before the servlet is first executed. In init, we make an initial connection to the database, keeping the connection around for future use.

  • doGet, which prints an error message indicating that only POST requests will be honored by this servlet.

  • doPost, which uses the database connection established by init to INSERT a new row into the BlogEntries table.

Modifying a servlet is different from modifying a CGI program in that the servlet container must reload the servlet from disk. Apache and mod_perl do not reload Perl modules by default; so too does Tomcat ignore modified servlets by default. You can change this behavior by setting the “reloadble” attribute to “true”; if you fail to do this, you will need to restart Tomcat each time you modify and recompile a servlet. Of course, there is a performance penalty when servlets are reloadable, which is why the Tomcat documentation suggests keeping them nonreloadable in production systems.

Our doPost method is the real workhorse in this servlet, taking input from the user's HTML form and inserting them into our table in PostgreSQL.

First we make sure that we have received the entry_headline and entry_text parameters from the user and the parameters aren't empty. If one or more is empty, then we create a message that indicates what was missing. Otherwise, we go ahead and create a PreparedStatement for inserting a new row into the database.

Perl programmers will see many similarities between JDBC and Perl's DBI. JDBC requires that we create a statement based on the database connection:

PreparedStatement statement =
      "INSERT INTO BlogEntries " +
      "  (entry_date, entry_headline, entry_text) " +
      "  VALUES " +
      "  (NOW(), ?, ?)"

Since we are using a PreparedStatement rather than a simple statement, we can use question marks (?) instead of variable values. The drivers for some databases, such as Oracle, take advantage of these placeholders and use them for greater speed. But even users of low-end databases can benefit from using placeholders because they ensure strings will be quoted correctly, even if they contain quotation marks or apostrophes:

statement.setString(1, entry_headline);
statement.setString(2, entry_text);
Notice how the first placeholder is numbered 1, rather than 0. Keep in mind that these two values are strings; if they were integers or floating-point numbers, we would have to use a different method on statement.

Next, we perform the actual insert:

int updateCount = statement.executeUpdate();

updateCount is assigned the number of rows that were affected by the executeUpdate() method. In this particular case, we were trying to insert a single row, so we compare updateCount with 1. If we were to use executeUpdate() to perform an SQL “UPDATE”, updateCount might contain a different number.

Finally, we catch exceptions that might have occurred during our use of SQL. We then print an error message, including the text of the exception. While printing such explicit messages to the end user might not be a good idea on a production web site, it is an excellent idea during development.



Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

Where is it?

Andy Canfield's picture

servlet.jar is now named servlet-api.jar. Use 'locate' to find it on your particular system.

White Paper
Linux Management with Red Hat Satellite: Measuring Business Impact and ROI

Linux has become a key foundation for supporting today's rapidly growing IT environments. Linux is being used to deploy business applications and databases, trading on its reputation as a low-cost operating environment. For many IT organizations, Linux is a mainstay for deploying Web servers and has evolved from handling basic file, print, and utility workloads to running mission-critical applications and databases, physically, virtually, and in the cloud. As Linux grows in importance in terms of value to the business, managing Linux environments to high standards of service quality — availability, security, and performance — becomes an essential requirement for business success.

Learn More

Sponsored by Red Hat

White Paper
Private PaaS for the Agile Enterprise

If you already use virtualized infrastructure, you are well on your way to leveraging the power of the cloud. Virtualization offers the promise of limitless resources, but how do you manage that scalability when your DevOps team doesn’t scale? In today’s hypercompetitive markets, fast results can make a difference between leading the pack vs. obsolescence. Organizations need more benefits from cloud computing than just raw resources. They need agility, flexibility, convenience, ROI, and control.

Stackato private Platform-as-a-Service technology from ActiveState extends your private cloud infrastructure by creating a private PaaS to provide on-demand availability, flexibility, control, and ultimately, faster time-to-market for your enterprise.

Learn More

Sponsored by ActiveState