Server-Side Java with Jakarta-Tomcat
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 (http://www.scripting.com/), 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 ftp://ftp.linuxjournal.com/pub/lj/listings/issue84/], 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 = con.prepareStatement( "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.
- Give new life to old phones and tablets with these tips!
- Readers' Choice Awards 2014 Poll
- Linux Systems Administrator
- Senior Perl Developer
- Technical Support Rep
- Memory Ordering in Modern Microprocessors, Part I
- [<Megashare>] Watch Mrs Brown's Boys Movie Online Full Movie HD 2014
- Source Code Scanners for Better Code