Web Applications with Java/JSP
A Note about Scoping
The Java Servlet Specification defines three data scopes: application, session and request. The JSP Specification adds a fourth one: page. Each of these scopes is a place where data can be stored by the Web application for use at any time. When object identifiers are used in expressions, they are looked up in each scoping level until an object is found. First, the page scope is searched, then the request, then the session and then the application. This is how tags like <c:forEach> can define new object names, and the tags within the body can access them.
The next tag, <c:out>, outputs a value in a Web-safe manner. If the value contains any < characters, they will be escaped to avoid nasty XSS attacks. The value of ${clientMap[item.clientId].name} is again an expression that tells <c:out> to take the client ID from the item object, use that to look up a value in the “clientMap”, and then get its name. The objects “item” and “clientMap” are both retrieved from the request attributes, and the <c:out> tag handles the expression evaluation and output escaping for us.
This page includes a form that allows us to enter new tasks. One of the most important attributes of the <form> is the “action”, which, of course, tells the form where the data should be sent. I use the <c:url> tag here to generate a URL for us. It may seem silly to use a tag when I simply could have used /timesheet/save-task as the value of the action attribute, but there are some subtle issues in play here, which must be taken into account. First, a Web application can be deployed into any “context path”, which means that the path to the servlet might actually be /my-timesheet/save-task. The <c:url> tag knows where the Web application has been deployed (courtesy of the request object, defined by the Servlet API) and can provide the appropriate path prefix to the URL. Second, <c:url> can encode the URL with a session identifier, which is essential to providing a good user experience for many Web applications. The <c:url> tag is smart enough to omit the session identifier from the URL if the client is using cookies to communicate the session identity to the server, but to include it in the URL as a fallback when cookies are unavailable. Sessions are another handy feature defined by the Servlet Specification, provided by the Servlet Container and accessible via the Servlet API.
Now that I've covered the display of the timesheet and the form that can be used to submit a new task, let's take a look at the code that accepts this form submission: SaveTaskServlet.java (Listing 5), which implements the “save-task” servlet, which is mapped to the URL /save-task.
Listing 5. SaveTasksServlet.java
package lj.timesheet;
import java.io.IOException;
import java.util.Date;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class SaveTaskServlet
extends BaseServlet
{
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
Integer taskId;
if(null == request.getParameter("id")
|| "".equals(request.getParameter("id").trim()))
taskId = null;
else
taskId = new Integer(Integer.parseInt(
request.getParameter("id")));
int clientId = Integer.parseInt(
request.getParameter("clientId"));
Date date = new Date();
String description = request.getParameter("description");
int duration = Integer.parseInt(
request.getParameter("duration"));
String username = request.getUserPrincipal().getName();
Task task = new Task(taskId, username, date,
clientId, description, duration);
try
{
save(task);
response.sendRedirect(response.encodeRedirectURL(
request.getContextPath() + "/tasks"));
}
catch (SQLException sqle)
{
throw new ServletException("Database error", sqle);
}
}
// see below
}
The SaveTaskServlet overrides the HttpServlet's doPost method so we can handle HTTP POST messages. It gathers the data from the request, made available through the request object's getParameter method, then creates a Task object and calls a helper method (defined later in the class) called “save”. After saving the new task, the user is redirected to the “tasks” servlet to view the updated list of tasks. Did you notice that the line of code performing the redirect calls response.encodeRedirectURL and prepends the context path to the target URI? This is precisely the tedium that is avoided in JSP files by using the <c:url> tag.
SaveTaskServlet also defines a “save” method that interacts with the database. While none of this code is servlet-oriented, it's instructive to see the power of some of Java's standard APIs. In this case, it's the JDBC API that gives us access to relational databases (Listing 6).
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
- Trying to Tame the Tablet
- New Products
- git-annex assistant
5 hours 53 min ago - direct cable connection
6 hours 16 min ago - Agreed on AirDroid. With my
6 hours 26 min ago - I just learned this
6 hours 30 min ago - enterprise
7 hours 40 sec ago - not living upto the mobile revolution
9 hours 51 min ago - Deceptive Advertising and
10 hours 27 min ago - Let\'s declare that you have
10 hours 28 min ago - Alterations in Contest Due
10 hours 29 min ago - At a numbers mindset, your
10 hours 30 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!