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.
Today’s modular x86 servers are compute-centric, designed as a least common denominator to support a wide range of IT workloads. Those generic, virtualized IT workloads have much different resource optimization requirements than hyperscale and cloud applications. They have resulted in a “one size fits all” enterprise IT architecture that is not optimized for a specific set of IT workloads, and especially not emerging hyperscale workloads, such as web applications, big data, and object storage. In this report, you will learn how shifting the focus from traditional compute-centric IT architectures to an innovative disaggregated fabric-based architecture can optimize and scale your data center.
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
| 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 |
| Non-Linux FOSS: Seashore | May 10, 2013 |
| Trying to Tame the Tablet | May 08, 2013 |
- RSS Feeds
- Making Linux and Android Get Along (It's Not as Hard as It Sounds)
- New Products
- Drupal Is a Framework: Why Everyone Needs to Understand This
- A Topic for Discussion - Open Source Feature-Richness?
- Home, My Backup Data Center
- Validate an E-Mail Address with PHP, the Right Way
- Tech Tip: Really Simple HTTP Server with Python
- New Products
- Trying to Tame the Tablet
- git-annex assistant
5 hours 1 min ago - direct cable connection
5 hours 24 min ago - Agreed on AirDroid. With my
5 hours 34 min ago - I just learned this
5 hours 38 min ago - enterprise
6 hours 8 min ago - not living upto the mobile revolution
8 hours 59 min ago - Deceptive Advertising and
9 hours 35 min ago - Let\'s declare that you have
9 hours 36 min ago - Alterations in Contest Due
9 hours 37 min ago - At a numbers mindset, your
9 hours 38 min 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!