Web Applications with Java/JSP
Listing 6. SaveTaskServlet.java
public Task save(Task task)
throws SQLException
{
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try
{
conn = getConnection();
if(null == task.getId())
{
// A new task
ps = conn.prepareStatement(
"INSERT INTO
task (owner, date, client_id,
description, duration)
VALUES (?,?,?,?,?)",
PreparedStatement.RETURN_GENERATED_KEYS);
ps.setString(1, task.getOwner());
ps.setTimestamp(2, new Timestamp(
task.getDate().getTime()));
ps.setInt(3, task.getClientId());
ps.setString(4, task.getDescription());
ps.setInt(5, task.getDuration());
ps.executeUpdate();
rs = ps.getGeneratedKeys();
if(!rs.next())
throw new SQLException(
"Expected auto-generated key, got none");
int taskId = rs.getInt(1);
if(rs.wasNull())
throw new SQLException(
"Got bogus auto-generated key");
task = new Task(taskId,
task.getOwner(),
task.getDate(),
task.getClientId(),
task.getDescription(),
task.getDuration());
}
else
{
ps = conn.prepareStatement(
"UPDATE task SET date=?, client_id=?,
description=?, duration=?
WHERE id=? AND owner=?");
ps.setTimestamp(1, new Timestamp(
task.getDate().getTime()));
ps.setInt(2, task.getClientId());
ps.setString(3, task.getDescription());
ps.setInt(4, task.getDuration());
ps.setInt(5, task.getId());
ps.setString(6, task.getOwner());
ps.executeUpdate();
}
return task;
}
finally
{
close(conn, ps, rs);
}
}
First, this method obtains a connection from a database connection pool and then determines if the Task is being created from scratch or updated (although our UI doesn't offer an “update” method yet, this class has been designed to allow updates). In each case, a parameterized SQL statement is prepared and then filled with data passed in from the calling code. Then, the statement is executed to write to the database, and a new object is passed back to the caller. In the case of a new task, the database-generated primary key is fetched from the statement after execution in order to pass it back to the caller.
Under normal circumstances, methods such as “save” would be split out into a separate class for easier organization, testing and architectural separation, but I've left them in the servlet classes for simplicity.
The example's full source code and prebuilt WAR file are available from the Linux Journal FTP server (see Resources), and I encourage you to download it and play around with it. I've also included quick installation instructions for Java and the Apache Tomcat servlet container, which will be required to run the example application.
Often, Perl and PHP-based Web applications are composed of self-contained scripts that perform one task: loading and displaying tasks, for instance. This kind of thing is entirely possible using nothing but JSPs. There are tag libraries that perform SQL queries, and you even can write Java code directly into a JSP, although I haven't covered it here because it's not necessary with the rich tools provided by the JSTL. On the other hand, there are some philosophical and practical reasons not to stuff everything into a single JSP. Most (Java) programmers subscribe to the “model-view-controller” architecture, where code is separated into logical units that model your problem domain (that would be the Task and Client objects in our example), provide views of your data (that's our JSPs) and control program flow (the servlets). This architectural separation actually leads to quite a few practical benefits, including:
Easier code maintenance: separation promotes code re-use and simplifies automated testing.
Error handling: if the controller is the only likely component to fail (due to bad input, db connection failure and so on), you don't have to worry about the view component failing during rendering, ruining your output.
Most Java projects are going to be split up in this way, so I wrote my example to illustrate this architecture, and I hope you consider using this architecture in your Java projects too.
Realizing the promise of Apache® Hadoop® requires the effective deployment of compute, memory, storage and networking to achieve optimal results. With its flexibility and multitude of options, it is easy to over or under provision the server infrastructure, resulting in poor performance and high TCO. Join us for an in depth, technical discussion with industry experts from leading Hadoop and server companies who will provide insights into the key considerations for designing and deploying an optimal Hadoop cluster.
Sponsored by AMD
Built-in forensics, incident response, and security with Red Hat Enterprise Linux 6
Every security policy provides guidance and requirements for ensuring adequate protection of information and data, as well as high-level technical and administrative security requirements for a system in a given environment. Traditionally, providing security for a system focuses on the confidentiality of the information on it. However, protecting the data integrity and system and data availability is just as important. For example, when processing United States intelligence information, there are three attributes that require protection: confidentiality, integrity, and availability.
Learn more about catching the bad guy in this free white paper.
Sponsored by DLT Solutions
Web Development News
Developer Poll
| Designing Electronics with Linux | May 22, 2013 |
| Dynamic DNS—an Object Lesson in Problem Solving | May 21, 2013 |
| Using Salt Stack and Vagrant for Drupal Development | May 20, 2013 |
| Making Linux and Android Get Along (It's Not as Hard as It Sounds) | May 16, 2013 |
| Drupal Is a Framework: Why Everyone Needs to Understand This | May 15, 2013 |
| Home, My Backup Data Center | May 13, 2013 |
- New Products
- Linux Systems Administrator
- Senior Perl Developer
- Technical Support Rep
- UX Designer
- Web & UI Developer (JavaScript & j Query)
- Designing Electronics with Linux
- Dynamic DNS—an Object Lesson in Problem Solving
- Making Linux and Android Get Along (It's Not as Hard as It Sounds)
- Using Salt Stack and Vagrant for Drupal Development
- Reply to comment | Linux Journal
6 hours 11 min ago - Reply to comment | Linux Journal
6 hours 27 min ago - Favorite (and easily brute-forced) pw's
8 hours 18 min ago - Have you tried Boxen? It's a
14 hours 10 min ago - seo services in india
18 hours 42 min ago - For KDE install kio-mtp
18 hours 42 min ago - Evernote is much more...
20 hours 43 min ago - Reply to comment | Linux Journal
1 day 5 hours ago - Dynamic DNS
1 day 6 hours ago - Reply to comment | Linux Journal
1 day 7 hours ago








Comments
Helpful article.
Thank you for bringing greater clarity to the Java Web world.
Cool article! Very insghtful.
This is an insightful article that expands horizons for Java users!