Pro Ajax and java (Struts and Ajax)
--Nathaniel T. Schutta and
Ryan Asleson
Struts is the granddaddy of all the Java web frameworks. Craig R. McClanahan launched
Struts in May 2000, with the 1.0 release following in July 2001. Since that time Struts has
arguably become the most popular Java web framework and due to its relatively old age is sometimes considered to be “legacy.” Struts pioneered the Model 2 model-view-controller (MVC) pattern that has become the standard among Java web frameworks. The Model 2 MVC pattern uses a servlet to control application flow, making it the controller. The controller typically delegates to a handler object that acts as the adapter between the request and the model. The model, of course, represents the application’s business objects or domain layer. After processing the request the controller forwards the request to the appropriate view, which is usually implemented using JSPs.
In addition to providing a Model 2 MVC implementation for Java web applications,
Struts provides a number of services that can help ease the burden of developing modern,
interactive web applications. Foremost among these services is the validation framework.
Before the availability of the Struts validator, we had to write all of our own validation
routines, such as verifying that the user filled out all of the information on the page or that a particular input field was in the correct format. The Struts validator will automatically perform validations on input fields based on definitions stored in an XML file, so instead of writing the tedious code to perform validations, you can simply specify validations in an XML file and the Struts validator will take care of the rest.
Struts Design
The following is not meant to be a complete Struts tutorial but rather a refresher on Struts’design and implementation. You’ve likely worked with Struts at some point in your career as a Java web application developer, but even if you haven’t, you’ll likely be familiar with its concepts as other Java web application frameworks (even homebuilt ones) often mirror Struts’ implementation.
The core of Struts is a servlet that acts as the controller within the MVC implementation.The Struts controller servlet is responsible for acting as a bridge between the application model and the web view. The controller passes requests to a request handler which is an instance of an Action class. The typical web application will use many different Action objects, and the controller servlet knows which Action to pass the request based on mappings in the struts-config.xml file.
The Action accesses the model to query or update the application’s state, or both. The Action itself should have no business logic and should simply delegate all of the grunt work to the model or a façade that accesses the model. By keeping business logic out of the Action objects, you can minimize the amount of coupling between your service/business tier and the web tier and from Struts in general.
Data from the HTTP request is passed to the Action object via an ActionForm object.
The ActionForm is a simple JavaBeans-style object that helps transfer data between the
model and the view. Struts automatically populates the ActionForm object with the parameters sent as part of an HTTP GET or POST operation. Thanks to the autopopulating of the ActionForm you don’t need to get the request parameters using the request object’s getParameter method.
The previous few paragraphs are all well and good, but like the old saying goes, a picture is worth a thousand words. Figure 5-1 is a UML sequence diagram that shows the key Struts classes and how they interact when servicing a web request.
The diagram in Figure 5-1 shows the interaction of the main Struts classes. As described previously, the Struts controller servlet handles all requests and delegates to the RequestProcessor the task of passing the requests to their appropriate handlers.
The RequestProcessor populates an instance of an ActionForm class from the request’s parameters, saving you from having to access the request object directly to retrieve the parameters.
Once populated, the ActionForm is subjected to two different methods for validating
the request parameters. First, Struts uses the Jakarta Commons Validator library to validate the ActionForm’s properties based on the validation rules defined in the validation.xml file, if any exist. Following that, if no validation errors occurred, the ActionForm’s validate method is called. Developers may override the base ActionForm’s validate method to validate the object’s properties.
Once all the validation routines complete, and assuming that there were no validation
errors, the Action is called. The Action is responsible for accessing the model and service layers where the real work is performed. The Action interacts with the ActionForm to access the request parameters and provide them to the service and model layers.
After accessing the service and model layers, the Action is responsible for preparing the response that is sent back to the browser. The Action populates the ActionForm or, as the diagram depicts, a helper object that contains the data will eventually appear in the view.
Finally the Action forwards the request to the view, which in most Java web applications is a JSP. Struts can work with a number of different views, including Velocity templates and XML/XSLT, in addition to JSP. The view populates itself using the data from the ActionForm and any helper objects.
In the end, the view renders itself as HTML that is sent back to the client browser. The result is a dynamically built web page that is built based on input by the user, in contrast to traditional static HTML pages that never change.
Ajax Validation
A key component of any web framework is the ability to validate information entered by
the user. Traditional thick-client applications often rely on custom input widgets that
only allow valid input. Many thick-client applications provide a date widget in which the
user can only enter numbers, and the widget also ensures that the input constitutes a
valid date; for example, it does not allow the user to enter a date greater than the number
of days in the specified month.
The web world has no concept of these types of complex input widgets. Many of the same effects can be handled with JavaScript, but writing the JavaScript to perform these duties can be tedious, error-prone, and time-consuming, not to mention unreliable—validation will not occur if the user has disabled JavaScript. As a result, in the web world, input validation has traditionally occurred on the server when the form data is posted to the server. The advantage of performing input validation on the server is that it’s guaranteed to always be executed (it runs regardless of whether JavaScript is enabled on the browser) and the validation routines can be as complex as needed, from simply verifying the correct format of a date string to accessing a database to ensure that a unique key is still unique.
The downside to performing validation on the server, of course, is that the validation is being performed on the server after the user has submitted the form. We would much rather perform the validation as soon as possible so any feedback can be presented to the
user as quickly as possible. Doing so provides a much richer and more interactive user
experience. But, alas, how can we seamlessly invoke server-side validation routines without posting the form and waiting for the whole page to refresh?
Ajax, of course! (Not that you didn’t already know.) One of the most common applications of Ajax is to invoke server-side validation routines to provide immediate feedback to the user. The following example demonstrates how the built-in Struts validators are easily leveraged using Ajax techniques.
Struts Validation
Struts allows developers to validate user input three ways. The first way is by using the
XML-based Commons Validator. Commons Validator allows form input validation to be
configured via rules defined in an XML file named validation.xml. Commons Validator
covers many of the simple yet repetitive validation routines such as ensuring that a particular element has received some input, that an input string consists of all numeric digits, or that an input string matches a predefined pattern. These cases and more are provided by Commons Validator, and all the developer needs to do is specify the rule (or rules) that must be applied to a particular input field. Much if not all of a form’s input validation can be performed by specifying rules in an XML file writing nary a line of Java code. Commons Validator is best used for simple validations such as a form element being required or an input string that must consist entirely of numeric digits.
The second way in which Struts allows for input validation is through the validate
method of any instance of the ActionForm class. All subclasses of the ActionForm may override the default implementation of the validate method, which does nothing. Struts always calls the ActionForm’s validate method after performing any validation specified in validation.xml but before passing the request to an Action class. The validate method is a great place to perform validation that is too complex to be covered by Commons Validator. If/else conditions that are nearly impossible to specify in validation.xml but relatively easy to do in Java code are a good example of validations that can be performed within an ActionForm’s validate method.
The final place in which validation can be performed is within a Struts Action class.
Like an ActionForm, validation that occurs within an Action must be written in Java. The
key difference is that the Action class has access to the application’s domain and service
tiers, so validations that involve querying the database or accessing business rules in the
domain tier are best placed within an Action. All Action classes can access the ActionMessages object to which error messages can be added.
Struts and Ajax Integration
Struts is an ideal framework on which to add Ajax interactions. Struts does a good job of
encapsulating all of the redundant details of MVC Model 2 development while still providing enough access to the “nuts and bolts” of the application so it can be customized as desired by the developer. One area in which Struts particularly shines is its flexibility when it comes to validating user input, and thanks to Struts’ various validation extension points, it can be easily integrated with Ajax.
This example demonstrates how well Struts validation can be integrated using Ajax.
The example is a fictional hotel room reservation system. The web page collects the necessary information like the desired dates, whether a smoking or nonsmoking room is desired,any special requests, and the customer’s name and telephone number. The example web page is shown in Figure 5-2.
Figure 5-2. A rather simple hotel reservation system
Listing 5-1 lists the JSP page that renders this screen. As you can see, there is no rocket science occurring within this JSP. Struts HTML custom tags like text and textarea are used to render the input elements, while the errors tag is used to display any error messages.
Listing 5-1. hotelReservation.jsp
<%@taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
<html:xhtml />
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Hotel Reservation System</title>
<script type="text/javascript" src="js/hotelReservation.js"></script>
<script type="text/javascript" src="js/prototype-1.4.0.js"></script>
</head>
<body>
<h1>Hotel Reservation System</h1>
<h3>* Required fields</h3>
<div id="errors"><html:errors /></div>
<html:form action="saveReservation.do" method="post"
styleId="reservationForm">
<table border="0">
<tbody>
<tr>
<td><label>* Arrival Date:</label></td>
<td><html:text property="arrivalDate" styleId="arrivalDate"
onblur="validateForm();" /></td>
</tr>
<tr>
<td><label>* Departure Date:</label></td>
<td><html:text property="departDate" styleId="departDate"
onblur="validateForm();" /></td>
</tr>
<tr>
<td><label>* Smoking Preference:</label></td>
<td><html:select property="smokingPref" styleId="smokingPref">
<html:option value="">Select One</html:option>
<html:option value="smoking">Smoking</html:option>
<html:option value="Non Smoking">
Non Smoking
</html:option>
</html:select></td>
</tr>
<tr>
<td><label>Special Requests:</label></td>
<td><html:textarea property="requests" styleId="requests" rows="6"
cols="50" /></td>
</tr>
<tr>
<td><label>* Name:</label></td>
<td><html:text property="name" styleId="name" /></td>
</tr>
<tr>
<td><label>* Telephone:</label></td>
<td><html:text property="telephone" styleId="telephone" /></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Submit" />
</td>
</tr>
</tbody>
</table>
</html:form>
</body>
</html>
As you might expect, there is some input validation that needs to occur on this page. All of the fields are required except for the Special Requests text area. In addition, the arrival and departure dates must be valid date formats, and the telephone number must be a valid telephone format. The input elements are validated when the form is submitted, and if any of the validations fail then the page is redisplayed with the error messages shown at the top of the page. So far so good.
Are there any other validations that could occur other than the ones that were just
mentioned? In this particular example, the answer is (as we say in Minnesota), “You betcha.” The user will want to know as soon as possible whether the desired room is available. For example, the user may request a smoking room for a certain date range. If the hotel has rooms available for that date range, but only nonsmoking rooms, then the user should be told that the selected date range and smoking combination is not available. At that point the user could either choose different dates or try the other smoking selection. Wouldn’t it be nice if the user could be told as soon as possible whether the selected date range and smoking selection yielded any available rooms?
Thanks to Ajax, we can indeed provide this functionality to the user. The simple input validations such as required fields being present or dates having the correct format could conceivably be done in the browser using some JavaScript, providing feedback before the user actually submits the form. In the case of checking room availability, we presumably need to access a server-side resource to determine whether the requested room is available.Ajax allows us to do just that without submitting the form.
The ordering of the input fields was specifically chosen to support this feature. By
including the arrival and departure dates and the smoking preference as the first items on
the page, the user will quickly see if the desired room is available. If it isn’t, then the user
can either change the selections or quit completely without having to fill in the other
input fields.
Ajax-Powered Validation
This example employs Ajax to determine whether the selected combination of rooms,
dates, and smoking preference yield any available rooms. If there are no available rooms
for the specified combination, then an error message should be shown to the user.
Since this example uses Ajax, there is bound to be some dreaded JavaScript required to make it work. This example uses the Prototype library that you learned about in Chapter 3 to take care of some of the more mundane JavaScript details like accessing input element values and creating and using XMLHttpRequest objects. You might be surprised to know that the JavaScript that makes all of this Ajax validation work is less than 50 lines long!
Listing 5-2 shows the entire JavaScript source code used in this example.
Listing 5-2. hotelReservation.js
function hasEntry(id) {
return $F(id).length > 0;
}
function isFormReadyForValidation() {
var ready = false;
if(hasEntry("arrivalDate")
&& hasEntry("departDate")
&& $F("smokingPref").length > 0) {
ready = true;
}
return ready;
}
function validateForm() {
var isReady = isFormReadyForValidation();
if(isReady) {
sendFormForValidation();
}
}
function sendFormForValidation() {
var queryString = Form.serialize("reservationForm");
queryString = queryString + "&ts=" + new Date().getTime();
var url = "validateReservation.do";
new Ajax.Request(url, {
asynchronous: true,
method: "get",
parameters: queryString,
onComplete: function(request) {
handleResponse(request.responseText);
}
});
}
function handleResponse(text) {
$("errors").innerHTML = text;
}
As you can see in Figure 5-2, there is only one button on the web page, and that is to
submit the form to the server. So how is the Ajax validation actually invoked? If you refer back to Listing 5-1, you’ll see that the arrival and departure dates and the smoking preference input fields all implement the onblur event handler. The onblur event handler invokes the specified JavaScript function whenever the input field loses focus. The idea is that the user will fill in the input fields in sequential order, and as soon as the arrival and departure dates and the smoking preference are filled in an Ajax request will be sent to the server to verify whether a room is available for the specified combination. The onblur event handlers for the arrival and departure dates and the smoking preference call the validateForm function shown in Listing 5-2.
The validateForm method first determines whether the arrival and departure dates and the smoking preference have been filled in by calling the isForReadyForValidation function. The isReadyForValidation function returns true if the arrival date, departure date, and smoking preference all have nonempty selections; it delegates to the hasEntry function for the arrival and departure dates.
Assuming that the isReadyForValidation function returns true, the validateForm function calls sendFormForValidation. The sendFormForValidation function handles the actual sending of the Ajax request. The function starts by using Prototype’s Form.serialize method to build a query string of the form values to be sent to the server. Following that, the current time stamp is appended to the query string to ensure that the URL is unique to prevent the browser from caching the request.
With the query string ready to go, the sendFormForValidation function uses Prototype’s Ajax.Request object to build and send the Ajax request. The Ajax request is sent to the validate.do URL using the GET method. It also specifies that the request be sent asynchronously and that the handleResponse function should be used to process the server’s response. The handleResponse method simply updates the innerHTML property of a div at the top of the page to show the error messages (if any) returned by the server.
That’s all the JavaScript that’s required! Thanks to the Prototype library it takes less
than 50 lines of code to implement this functionality, which is a small price to pay for the
order of magnitude increase in richness and usability we are adding to the application.
The browser side is now done. You’ve seen the HTML that makes up the home page
and the JavaScript that powers the Ajax request. Now you’ll turn your attention to the
server side where Struts will help us handle the request and perform the necessary
validations.
Implementing Struts
The client-side work with the JavaScript was the hardest part of this whole exercise. If you’ve ever worked with Struts or another action-based Web MVC framework the rest of this example will come very easily to you.
The heart of Struts is found in the struts-config.xml file. The struts-config.xml file is
the glue that binds the various actions, action forms, requests, and validations together to
make a usable web application. We’ll be referring to this example’s struts-config.xml file
a lot over the next several pages, so it’s best that you see it right away. Listing 5-3 shows the struts-config.xml file used in this example.
Listing 5-3. struts-config.xml
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.2//EN"
"http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd">
<struts-config>
<form-beans>
<form-bean name="reservationForm"
type="com.proajax.chapt5.validation.ui.ReservationForm"/>
</form-beans>
<action-mappings>
<action path="/reservation"
type="org.apache.struts.actions.ForwardAction"
name="reservationForm"
scope="request"
parameter="/hotelReservation.jsp" />
<action path="/validateReservation"
type="com.proajax.chapt5.validation.ui.ValidateReservationAction"
name="reservationForm" validate="true"
input="/jsp/validation/reservationErrors.jsp" >
<forward name="valid" path="/jsp/validation/blank.jsp"/>
<forward name="invalid"
path="/jsp/validation/reservationErrors.jsp"/>
</action>
<action path="/saveReservation"
type="com.proajax.chapt5.validation.ui.SaveReservationAction"
name="reservationForm"
validate="true"
input="/hotelReservation.jsp">
<forward name="success"
path="/jsp/validation/reservationSuccessful.jsp"/>
<forward name="fail" path="/hotelReservation.jsp"/>
</action>
</action-mappings>
<controller
processorClass="org.apache.struts.tiles.TilesRequestProcessor"/>
<message-resources parameter="MessageResources" />
<plug-in className="org.apache.struts.tiles.TilesPlugin" >
<!-- Path to XML definition file -->
<set-property property="definitions-config"
value="/WEB-INF/tiles-defs.xml" />
<!-- Set Module-awareness to true -->
<set-property property="moduleAware" value="true" />
</plug-in>
<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
<set-property
property="pathnames"
value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml"/>
</plug-in>
</struts-config>
This struts-config.xml file was constructed by modifying the file that’s bundled with
the blank Struts starter application that comes with the Struts download. The most import antsections of this file are the form-beans and action-mappings elements. The form-beans element has zero to many form-bean child elements that declare the ActionForm classes that are used in the application.
For this application there is a single action form: the ReservationForm class.The ReservationForm class is a simple JavaBeans-style object that extends the ValidatorActionForm class and provides public getter and setter methods for each of the form elements. The ReservationForm class source code is shown in Listing 5-4.
Listing 5-4. ReservationForm.java
package com.proajax.chapt5.validation.ui;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.validator.ValidatorActionForm;
public class ReservationForm extends ValidatorActionForm {
private String arrivalDate;
private String departDate;
private String smokingPref;
private String requests;
private String name;
private String telephone;
private DateFormat parser = new SimpleDateFormat("MM/dd/yyyy");
public String getArrivalDate() {
return arrivalDate;
}
public Date getArrivalDateAsDate() {
try {
return parser.parse(arrivalDate);
}
catch(ParseException e) {
return null;
}
}
public void setArrivalDate(String arrivalDate) {
this.arrivalDate = arrivalDate;
}
public Date getDepartDateAsDate() {
try {
return parser.parse(departDate);
}
catch(ParseException e) {
return null;
}
}
public String getDepartDate() {
return departDate;
}
public void setDepartDate(String departDate) {
this.departDate = departDate;
}
public String getSmokingPref() {
return smokingPref;
}
public void setSmokingPref(String smokingPref) {
this.smokingPref = smokingPref;
}
public boolean isSmokingRequest() {
return smokingPref.equalsIgnoreCase("smoking");
}
public String getRequests() {
return requests;
}
public void setRequests(String requests) {
this.requests = requests;
}
public ActionErrors validate(ActionMapping mapping
, HttpServletRequest request) {
ActionErrors errors;
errors = super.validate(mapping, request);
DateFormat parser = new SimpleDateFormat("MM/dd/yyyy");
try {
Date arrival = parser.parse(arrivalDate);
Date departure = parser.parse(departDate);
if(departure.before(arrival)) {
errors.add(ActionErrors.GLOBAL_MESSAGE
, new ActionMessage("errors.departure.before.arrival"
, true));
}
}
catch (Exception e) {
// Do nothing -- date format validation is handled in
// validation.xml.
}
return errors;
}
public String getName() {
return name;
}
168 CHAPTER 5 ■ STRUTS AND AJAX
public void setName(String name) {
this.name = name;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
}
Astute readers will notice that the ReservationForm class extends the Struts ValidatorActionForm class instead of the ValidatorForm class. This choice was quite deliberate. Both ValidatorActionForm and ValidatorForm provide basic field validation based on the validation.xml file. For the ValidatorActionForm, the key passed into the validator is the action element’s path attribute, which should match the form-bean’s name attribute. For the ValidatorForm, the key passed into the validator is the action element’s name attribute, which should match the form-bean’s name attribute. Put another way, extending ValidatorActionForm means that the validation rules from validation.xml (Listing 5-6) will be applied to requests based on the request’s path; extending ValidatorForm means that validation rules from validation.xml will be applied to requests based on the form bean used by the request.
The real meat of the struts-config.xml file comes in the action-mappings section.
Each individual action element is the real glue that binds a request to its form bean and
specifies the location to where the request should be directed following the handling of
the request by the Action class. The first action listed is the reservation action, which
simply displays the empty reservation page.
The next action in Listing 5-4 is the validateReservation action. You probably recall
that this action is the destination URL of the Ajax request from Listing 5-2 that handles the validation of the arrival and departure dates and smoking preference combination. There’s a lot going on in this action mapping, so we’ll try to break it down and explain it piece by piece.
The validateReservation action is configured by the name attribute to use the reservationForm form bean—no surprises there. The validate attribute is set to true so that the form bean’s validate method is called before calling the Action object. The input attribute of the validateReservation action is a key piece of the puzzle.
The input attribute tells Struts the response to send if any validation exceptions were
recorded. In non-Ajax applications this attribute usually points to the same page that submitted the request to the action. In non-Ajax applications the JSP that submitted the
request often uses the Struts custom JSP tags to list the error messages when the page is
rendered. However, this example uses Ajax, so the entire page will not be redrawn if any
validation errors occur. Instead, only a small section of the page will be updated to list the
error messages. Refer back to Listing 5-1. At the top of the page there is a div tag with an
id attribute value of errors. This is the area in which any errors that are returned by the
server will be placed. You should also recall that the handleResponse JavaScript function in Listing 5-2 updates the errors div with the response from the server.
For the validateReservation action the input attribute points to the reservationErrors.jsp file, which is shown in Listing 5-5. It uses the Struts custom tags to
render any error messages that have been logged during the validation routine. Since this
is an Ajax request that will only update a small part of the page, that’s the only output it
needs to render.
Listing 5-5. reservationErrors.jsp
<%@taglib uri="http://struts.apache.org/tags-logic" prefix="logic" %>
<%@taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
<%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>
<logic:messagesPresent>
<ul>
<html:messages id="error">
<li style="color:red;">
<bean:write name="error"/>
</li>
</html:messages>
</ul>
</logic:messagesPresent>
The error messages are built as an unordered list. This example uses the logic:messagesPresent, html:messages, and bean:write tags to build the unordered list of errors. Another option is to simply use the html:errors JSP tag, but the HTML markup for this tag must be specified in the messages properties file.
The validateReservation action has two forward elements: one for the valid case (when no validation messages were recorded) and one for the invalid case. The path for the valid case is a JSP file named blank.jsp. As its name suggests, this file contains almost no content—in fact, its only contents are a nonbreaking space. The nonbreaking space blanks out any messages that may already exist on the page. For example, if the user entered a date in an invalid format and received a validation error saying as much, the error message should be removed from the page as soon as the user fixes the date and tabs off of the input field.
Whew! That brings us to the end of the validateReservation action in the struts-config.xml file. There are a lot of things happening in those eight lines of XML,so if you’re still a little foggy on some of the items, you should reread this section until you
feel comfortable with what’s happening.
Now is a good time to talk about the actual validation implementation. For the past several pages you’ve been hearing about how user input will be validated using an Ajax request, and you’ve seen how the struts-config.xml file was set up to wire everything together, but so far you haven’t seen the actual validation implementation. Remember the discussion earlier regarding the different ways by which Struts can validate form input, that it could be done through Commons Validator, the form bean’s validate method, or even the Action class itself? This example uses a combination of all three. Simple format validation occurs using Commons Validator with the validation rules described in the validation.xml file. Input validation that is too complex for Commons Validator happens in the form bean’s validate method. Finally, validation that requires accessing the service and data tiers occurs in the Action class.
You can think of Commons Validator and its integration with Struts as the first line of defense when it comes to input validation. Without writing a line of Java code you cover a large portion of your application’s validation needs by editing an XML file. This example uses Commons Validator to perform the simple formatting validations that must occur whenever form input is submitted to the server, whether it be through an Ajax request or a normal form submission.
Listing 5-6 lists the validation.xml file used in this example. This example validates two types of form submissions: the Ajax request that validates the arrival and departure dates format and whether their combination with the smoking preference yields any available rooms, and the “normal” form submission where the entire form is submitted.
Listing 5-6. validation.xml
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE form-validation PUBLIC
"-//Apache Software Foundation//DTD Commons Validator Rules
Configuration 1.1.3//EN"
"http://jakarta.apache.org/commons/dtds/validator_1_1_3.dtd">
<form-validation>
<global>
<constant>
<constant-name>phoneFormat</constant-name>
<constant-value>^\(?\d{3}\)?\s|-\d{3}-\d{4}$</constant-value>
</constant>
CHAPTER 5 ■ STRUTS AND AJAX 171
<constant>
<constant-name>dateFormat</constant-name>
<constant-value>^\d{1,2}/\d{1,2}/\d{4}$</constant-value>
</constant>
</global>
<formset>
<form name="/validateReservation">
<field property="arrivalDate" depends="required, mask">
<msg key="errors.date" name="mask"/>
<arg0 key="label.arrival.date" resource="true"/>
<arg1 key="format.date"/>
<var>
<var-name>mask</var-name>
<var-value>${dateFormat}</var-value>
</var>
</field>
<field property="departDate" depends="required, date">
<msg key="errors.date" name="mask"/>
<arg0 key="label.depart.date" resource="true"/>
<arg1 key="format.date"/>
<var>
<var-name>mask</var-name>
<var-value>${dateFormat}</var-value>
</var>
</field>
</form>
<form name="/saveReservation">
<field property="arrivalDate" depends="required, mask">
<msg key="errors.date" name="mask"/>
<arg0 key="label.arrival.date" resource="true"/>
<arg1 key="format.date"/>
<var>
<var-name>mask</var-name>
<var-value>${dateFormat}</var-value>
</var>
</field>
172 CHAPTER 5 ■ STRUTS AND AJAX
<field property="departDate" depends="required, mask">
<msg key="errors.date" name="mask"/>
<arg0 key="label.depart.date" resource="true"/>
<arg1 key="format.date"/>
<var>
<var-name>mask</var-name>
<var-value>${dateFormat}</var-value>
</var>
</field>
<field property="smokingPref" depends="required">
<arg0 key="label.smoking.pref" resource="true"/>
</field>
<field property="name" depends="required">
<arg0 key="label.name" resource="true"/>
</field>
<field property="telephone" depends="required, mask">
<msg key="errors.invalid.telephone.format" name="mask"/>
<arg0 key="label.telephone" resource="true"/>
<var>
<var-name>mask</var-name>
<var-value>${phoneFormat}</var-value>
</var>
</field>
</form>
</formset>
</form-validation>
The first form listed is the validateReservation form. This form is identified by the name attribute on the form element. Because the ReservationForm class extends ValidatorActionForm, the name attribute of the form element refers to the URL to which
the request is sent—in this case, validateReservation.do. The validation that occurs on this form is the format of the arrival and departure dates and that the arrival and departure dates and smoking preference are required. Figure 5-3 shows the error messages that occur when the user enters invalid arrival and departure dates, selects a smoking preference, and tabs off of the smoking preference select field.
The second form, which is identified by the saveReservation name attribute, performs the validation for when the complete form is explicitly submitted by the user using the Submit button. It includes the same validation for the arrival and departure dates as the validateReservation form but adds required validations for the name and telephone number in addition to validating the format of the telephone number.
FORM SUBMISSION
ALWAYS VALIDATE USER INPUT ON FORM SUBMISSION
Be sure to always validate user input when the form is submitted to the server, even if the form’s fields have been validated using Ajax techniques. Why?
The user may be able to disable validation via Ajax but won’t be able to disable validation on the server. The user could have JavaScript disabled within the browser, which would render the validation via Ajax useless. Major problems could occur if the form is submitted with invalid data due to the failure of Ajax validation. However, if the form validations are repeated on the server when the form is submitted, then these problems will be avoided.
This example uses regular expressions to validate the date and telephone formats whose formats are listed as constants at the top of the file. In addition, the error messages and labels are externalized to a properties file named MessageResources.properties. Note that this file is specified in the struts-config.xml file! This file holds the standard error message format used by Commons Validator, and user-defined messages can also be placed here. Listing 5-7 lists the custom labels and error messages added the standard MessageResources.properties file.
Listing 5-7. Additions to the MessageResources.properties File Specific to This Example
label.arrival.date=Arrival Date
label.depart.date=Departure Date
label.smoking.pref=Smoking Preference
label.name=Name
label.telephone=Telephone Number
format.date=MM/DD/YYYY
errors.departure.before.arrival=Arrival date must occur before departure date.
errors.invalid.date.format=Invalid date format.
errors.invalid.telephone.format=Invalid telephone format.
errors.reservation.not.available=The requested reservation is not available.
You’ve now seen the first layer of validation that was performed by Commons Validator.The next layer of validation occurs in the form bean itself. Refer back the source code for the ReservationForm class shown in Listing 5-4. Here, the validate method ensures that the arrival date entered by the user occurs before the entered departure date. We don’t want potential guests to check out before they arrive. This is a great example of a validation that isn’t easily handled by Commons Validator but can be easily accomplished with Java code.
If no validation errors were recorded by Commons Validator or the validate method of the ReservationForm, then the request is passed to the Action handler. The Ajax request is handled by the ValidateReservationAction class. This class extends the Struts Action class and overrides the execute method to validate the combination of arrival date, departure date, and smoking preference submitted by the user. More specifically, the execute method accesses the service tier and asks it to verify whether any rooms are available for the request arrival and departure dates and smoking preference. The source code for the ValidateReservationAction class is shown in Listing 5-8.
Listing 5-8. ValidateReservationAction.java
package com.proajax.chapt5.validation.ui;
import com.proajax.chapt5.service.ReservationService;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
public class ValidateReservationAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm actionForm
, HttpServletRequest request, HttpServletResponse response)
throws Exception {
ReservationForm form = (ReservationForm) actionForm;
ReservationService service = new ReservationService();
boolean isAvailable =
service.isReservationAvailable(form.getArrivalDateAsDate()
, form.getDepartDateAsDate()
, form.isSmokingRequest());
ActionMessages errors = this.getErrors(request);
if(!isAvailable) {
errors.add(ActionMessages.GLOBAL_MESSAGE
, new ActionMessage("errors.reservation.not.available"
, true));
}
saveErrors(request, errors);
ActionForward forward = null;
if(errors.size() > 0) {
forward = mapping.findForward("invalid");
}
else {
forward = mapping.findForward("valid");
}
return forward;
}
}
The Action class is the most logical place to put this type of validation routine. Because it requires Java code, it can’t be done by Commons Validator, at least not without writing a custom validator class. It could technically be done in the form bean, but this doesn’t make sense because the form bean is intended to be a fairly “dumb” object that doesn’t contain too much business logic. The Action, however, is intended from the start to be the bridge between the web tier and the service and data tiers. Since this validation requires accessing a database to see if the requested room is available, it makes the most sense to place the validation here in the Action class.
You’ve probably noticed that the execute method doesn’t actually perform any of the
validation itself. Instead, it calls on a ReservationService object that performs the actual
lookup to see if there is a room available matching the requested arrival and departure
and smoking preference. To keep the example simple, this method uses a random algorithm that will indicate that the desired room is unavailable approximately one-third of the time. The source code for the ReservationService is shown in Listing 5-9.
Listing 5-9. ReservationService.java
package com.proajax.chapt5.service;
import com.proajax.chapt5.exception.ReservationNotAvailableException;
import java.util.Date;
import java.util.Random;
public class ReservationService {
private static Random random = new Random();
public boolean isReservationAvailable(Date arrival, Date departure
, boolean isSmoking) {
//Of course a real implementation would actually check if the desired
//reservation was available. Here, just do it randomly so the
//reservation is unavailable about 1/3 of the time.
return ! ((random.nextInt(100) % 3) == 0);
}
public void saveReservation(Date arrival, Date departure
public void saveReservation(Date arrival, Date departure
, boolean isSmoking, String requests
, String name, String telephone)
throws ReservationNotAvailableException {
if(!isReservationAvailable(arrival, departure, isSmoking)) {
throw new ReservationNotAvailableException();
}
// Logic to actually save the reservation goes here.
}
}
Over the last several pages we’ve discussed a lot of concepts and code, so we should
step back for a minute and think about what we’ve been trying to accomplish. The main
goal of this example is to provide Ajax-enabled form validation so that the user can receive immediate feedback regarding their input into the form. Not only does the validation perform simple validations like ensuring that input dates are in the correct format, but also that the requested combination of arrival date, departure date, and smoking preference yield an available room. Ajax is used to submit these three items to the server for validation as soon as the user tabs off any of the three fields. If the user enters valid dates for the arrival and departure dates, selects a smoking preference, and tabs off of the smoking preference select field, and the server determines that a room matching that combination is not available, an error message alerting the user to this fact is displayed at the top of the page, as shown in Figure 5-4.
Of course, this mini-application wouldn’t be complete if the user couldn’t actually try to save a reservation. After entering all of the required information, the user can click the Submit button to save the reservation. Of course, all of the input validation executes to ensure that all of the required input fields have valid selections and that dates and telephone numbers are in the correct format. You’ve already seen these validations in the validation.xml file and in the form bean’s validate method.
The struts-config.xml file is configured to send the save request to the SaveReservationAction class. As in the ValidateReservationAction class you saw before, this class extends the Struts Action class and overrides the execute method. The execute method attempts to save the request reservation to the database by delegating the task to the saveReservation method of the ReservationService class, which you saw previously in Listing 5-9. Notice how the saveReservation method still checks to make sure that the requested reservation is still available. If it’s not, a ReservationNotAvailableException is thrown and an error message is displayed.
If all of the input data is in the correct format and a reservation is available, the reservation is saved and the user is shown a confirmation page. The confirmation page, shown
in Listing 5-10, simply echoes the data entered by the user. The results of a successful reservation are shown in Figure 5-5.
Listing 5-10. reservationSuccessful.jsp
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Hotel Reservation Confirmed</title>
</head>
<body>
<h1>
Congratulations! Your reservation is confirmed.
</h1>
<ul>
<li>Arrival Date: ${reservationForm.arrivalDate}</li>
<li>Departure Date: ${reservationForm.departDate}</li>
<li>Smoking Preference: ${reservationForm.smokingPref}</li>
<li>Special Requests: ${reservationForm.requests}</li>
<li>Name: ${reservationForm.name}</li>
<li>Telephone: ${reservationForm.telephone}</li>
</ul>
</body>
</html>
Figure 5-5. A successful reservation
Struts and Ajax Design Considerations
The example presented in this chapter represents an in-depth case study of integrating
Ajax into Struts-based applications. You’ve seen how the existing features of Struts can be expanded and given new life with the addition of Ajax techniques.
This example showed building an application from the ground up that leveraged Ajax in specific areas to enhance the user experience. However, this functionality could have been just as easily added to an existing application. Imagine for a moment how this application would have worked without Ajax: there would have been no immediate feedback to the user if the requested room combination (arrival date, departure date, and smoking preference) was not available. The user would have completed the entire form, clicked the Submit button, and then if the requested room was not available, the page would have been re-rendered with the error message at the top of the page.
In this scenario, the code making up the application would be nearly identical to the
Ajax-, enabled version. The application would still have the JSPs that render the user interface, an ActionForm that contained the user input, an Action that handled the Submit
request, a service that actually performed the work of making the reservation, and simple
form validation using Commons Validator.
The Ajax-enabled version simply adds a new Action that specifically handles the Ajax request and a couple of JSPs to render the Ajax response. The validation.xml file includes validation for the Ajax request, and even those rules are near-copies of the rules for the complete form submission. It was all topped off with less than 50 lines of JavaScript to make it all work, and that JavaScript is trivial in nature thanks to the use of the Prototype library. The solution demonstrated here also degrades gracefully when JavaScript is disabled in the browser. If JavaScript is disabled, the onblur event handlers will never be invoked, preventing the Ajax validation from occurring. However, the form is still validated when it’s submitted to the server, which prevents errors caused by invalid input.
The point is that adding Ajax to your existing Struts applications can be a relatively
straightforward task that will likely produce a chorus of applause from your users. In the
days before Struts became popular, building web applications was rather difficult due to
the necessity of working with the low-level servlet API. Struts removed many of the barriers to rapidly building web applications using Java. No longer was it necessary to build a slew of servlet classes and constantly modify the web.xml file with each new servlet.
With Struts easing the burden of working with the servlet API, you can exploit it by
using Ajax to asynchronously communicate from the browser to the server. Struts makes
it easy to write code on the server side that handles the incoming Ajax request. In fact, if
you’re adding Ajax to an existing Struts application, you’ll likely only have to write a new Action class and wire it together with existing objects and services.
Because of this, there’s no reason not to add some Ajax goodness to your existing Struts applications. Search your applications for areas in which the entire page is refreshed for the sake of updating a small part of the page. Possible examples of this include displaying simple validation messages, sorting a table in response to the user clicking a table header, or adding the results of a search to the page. Your users will love you for updating these scenarios to use Ajax instead of the traditional full-page refresh. Struts makes it easy to build the server-side components, and combined with any of the Ajax frameworks and libraries you’ve seen from previous chapters, you can add Ajax to your applications in no time with minimal fuss.
The Future of Struts
A contemporary discussion of Struts would not be complete without discussing the future of Struts development, support, and adoption. At the time of this writing Struts is over five years old, and many within the development community consider Struts to be a legacy framework. The problems they cite with Struts include the inability to use domain objects without duplicate form objects, the difficulty testing Struts modules outside of the container, and the forced inheritance of ActionForms and Actions, among others.
In addition to the number of modern, direct competitors to Struts, including Spring
MVC, Wicket, and Tapestry, there are a few projects whose goal is to build the “next generation” of Struts. We’ll briefly take a look at some of these projects so you can get a feel for what’s happening it the Struts development world.
Struts 1.3 and Beyond
Even though the current Struts Action framework is considered by some to be legacy code, there are still plans to keep improving it as long as volunteers are willing to do so.
The Struts 1.x Roadmap (http://struts.apache.org/struts-action/roadmap.html) lists several possible improvements to Struts. Struts 1.3 aims to implement the “Struts Chain” request processor, meaning that Struts would implement the Chain of Responsibility design pattern for handling requests. This design would be more flexible than the
current Action-based request handling.
Other potential enhancements to Struts 1.x include support for portlets, combining
DTDs, a populate method on the ActionForm, support for multiple controllers, and an
alternate configuration file.
Struts Shale
Shale (http://struts.apache.org/struts-shale) is a proposal for a modern web application that is fundamentally based on JavaServer Faces. Its goal is to ease the adoption of JavaServer Faces for developers and to provide fine-grained service options that can be combined and extended to meet complex application requirements. The core technologies on which Shale is based are JDK 1.4, servlet API 2.4, JSP 2.0, and JavaServer Faces 1.1.
Shale includes the following features (and more):
• A ViewController that backs a Java class with each JavaServer Faces view that provides predefined event handlers for events significant to an application.
• A Dialog Manager that defines a conversation with a user that requires multiple HTTP requests.
• The Application Manager is a traditional application-wide front controller that applies features to every HTTP request.
• Built-in support for Ajax.
• Integration with the Spring framework.
• A built-in test framework consisting of mock objects and a JUnit test case base.
As you can see, Shale is being designed and built from the ground up to be a modern and full-featured MVC framework that utilizes the latest techniques and technologies. Since it’s fundamentally based on JavaServer Faces, you’ll want to check out Shale if you plan on making use of JavaServer Faces.
Struts Ti
The goal of Struts Ti (http://wiki.apache.org/struts/StrutsTi) is to build a simplified MVC framework that allows the developer better access to the underlying servlet environment. The key goal of Struts Ti is simplicity and it aims to provide the same level of ease of use as Ruby on Rails.
The major announcement of Struts Ti is that it includes a merger between Struts and WebWork (www.opensymphony.com/webwork), meaning that Struts Ti will start with the WebWork 2.2 code base. Another goal of Struts Ti is to provide a Struts 1.x compatibility layer to assist in migrating applications to the new framework.
At the time of this writing Struts Ti is in the Struts sandbox for possible eventual acceptance as a Struts subproject. The Struts Ti developers warn that Struts Ti is not yet an official Struts subproject and that it not ready for operational use.
Summary
As the granddaddy of all Java web MVC frameworks, Struts has built up a loyal following of developers and has innumerable applications built on top of it. Struts frees the developer from having to write directly to the servlet API and constantly edit the web.xml file. Struts provides built-in support for validation, internationalization, and a set of JSP custom tags that ease the burden of building rich, web-enabled Java applications.
Ajax integrates very easily with Struts. An Ajax request can call any Struts action by
simply sending the request to the correct URL. Once there, the Ajax request is handled the same as any other HTTP request. This, of course, means that the Ajax request has the same access to the Struts validation routines, form beans, and actions, and the benefits
provided by each.
Struts and Ajax work very well together, and existing Struts applications can be easily extended by adding Ajax functionality. In many cases Ajax-style interactions can be added to an existing Struts application by adding an Action that reuses existing functionality.