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
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.
Sponsored by ActiveState
Web Development News
Developer Poll
| Non-Linux FOSS: libnotify, OS X Style | Jun 18, 2013 |
| Containers—Not Virtual Machines—Are the Future Cloud | Jun 17, 2013 |
| Lock-Free Multi-Producer Multi-Consumer Queue on Ring Buffer | Jun 12, 2013 |
| Weechat, Irssi's Little Brother | Jun 11, 2013 |
| One Tail Just Isn't Enough | Jun 07, 2013 |
| Introduction to MapReduce with Hadoop on Linux | Jun 05, 2013 |
- Containers—Not Virtual Machines—Are the Future Cloud
- Non-Linux FOSS: libnotify, OS X Style
- Linux Systems Administrator
- Validate an E-Mail Address with PHP, the Right Way
- Lock-Free Multi-Producer Multi-Consumer Queue on Ring Buffer
- Senior Perl Developer
- Technical Support Rep
- UX Designer
- Introduction to MapReduce with Hadoop on Linux
- RSS Feeds
- One advantage with VMs
5 min 20 sec ago - about info
38 min 29 sec ago - info
39 min 28 sec ago - info
40 min 22 sec ago - info
42 min 27 sec ago - info
43 min 31 sec ago - abut info
45 min 12 sec ago - info
46 min 11 sec ago - info
47 min 43 sec ago - info
48 min 36 sec 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!