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.
- Readers' Choice Awards 2013
- The Geek's Guide to the Coolest 2013 Holiday Gifts
- A Plexible Pi
- Sublime Text: One Editor to Rule Them All?
- Swap Your Laptop for an iPad + Linode
- RSS Feeds
- Raspberry Pi: the Perfect Home Server
- Linux Kernel News - November 2013
- Mars Needs Women
- Tech Tip: Really Simple HTTP Server with Python
- "RasPlex Linux-based OS
7 hours 1 min ago
- Clarification; RasPlex is not
13 hours 50 min ago
- Clarification; RasPlex is not
13 hours 52 min ago
- Starting the conversation is the first step.
14 hours 52 min ago
16 hours 38 min ago
16 hours 38 min ago
- Nice but....
17 hours 1 min ago
- great specs
23 hours 30 min ago
- Reply to comment | Linux Journal
1 day 36 min ago
- rilakkuma onesie
1 day 3 hours ago