Apply DWR to Data Validation in an AJAX Application : Page 4

Learn how to use the open source Direct Web Remoting (DWR) library to dynamically generate JavaScript that includes a callback function parameter for web page updates in AJAX applications.

by Deepak Vohra

Apr 26, 2007

Page 4 of 4

Scripted Form
The JavaScript functions and the user registration entry form are specified in the userregistration.jsp file. You need to include the JavaScript file created from the UserRegistration Java class in userregistration.jsp. The JavaScript file for the UserRegistration class was specified as UserRegistration in dwr.xml. Include the UserRegistration.js:

The webapp1 element specifies that the web application's WAR file will be created from the DWR application. Be sure to include engine.js and util.js in the userregistration.jsp; engine.js is required to marshal invocations from the dynamically generated JavaScript functions for the Java class methods. Create a DWR engine in engine.js this way:

var DWREngine = dwr.engine;

The DWR engine can be used to specify options such as timeout or specify handlers such as errorHandler, exceptionHandler, and callback. The util.js JavaScript file contains functions to update a web page using data returned by the server. Table 1 lists some of the commonly used util.js functions.

Table 1. JavaScript Update Functions

Function

Description

$()

Retrieves an element by ID and is the equivalent of document.getElementById

getText(id)

Returns the displayed text for a select list

getValue(id)

Returns the value of an element

getValues()

Returns values for a JavaScript object that contains a collection of name/value pairs; the name/value pairs are the element IDs and their values

setValue(id, value)

Sets the value of an element

setValues()

Sets the values of a collection of name/value pairs representing element IDs and their values

Create an HTML table in userregistration.jsp that consists of fields for the user ID and password. The User ID field value is validated when the value is specified using the onkeyup event handler. Use the onkeyup function to invoke the JavaScript function validateUserId():

In the validateUserId() function retrieve the value of the userId field, and invoke the remote method validate() using a callback function as an argument in the method. The callback function can be the first parameter or the last parameter specified, but it is recommended to be specified as the last parameter. Note, however, that some of the examples on the DWR web site specify the callback function as the first parameter. Despite the recommendation, specify the callback function as the first parameter in the application example. The validate() method is invoked with the callback function getValMessage() and the userId value:

The callback function can also be specified as a call metadata object:

UserRegistration.validate(userId, {
callback:function(msg) { }
});

When the AJAX request is complete the callback getValMessage() function is invoked with the boolean returned by the validate() method as an argument. If the boolean returned is true, implying that the user ID is not defined in the database, display the validation message "User ID is valid"; if the boolean is false, display the validation message "User ID is not valid."

If the user ID is valid, specify the Password field and submit the user entry with the Submit button, which invokes the addUserRegistration() JavaScript function. Use this function to retrieve the values for the different form fields, and invoke the remote method updateUserTable() with a callback function and the field values as parameters. Use the Java class updateUserTable() method to obtain a connection with the MySQL database and create a user entry. The clearForm callback function clears the user entry form. The useregistration.jsp is shown in Listing 3.

Figure 3. Deploy to the JBoss Server: After you create the web application from the DWR application, you can deploy it to the JBoss application server connection that was established previously.

Using the connection you created earlier, create a web application from the DWR application and deploy it to the JBoss server. To create a WAR file deployment profile, select File-->New, and then select General-->Deployment Profiles-->WAR File. Click OK, specify the WAR file name, webapp1, and click OK. Then click OK in the WAR Deployment Profile Properties window. Right-click the deployment profile, and select Deploy To-->JBossConnection to deploy the WAR file deployment profile to JBoss (see Figure 3). The webapp1 EAR file deploys to the deploy directory of the default server.

Callback Validation
JDeveloper doesn't provide for deploying the web application as a WAR file. Therefore, you will need to modify the EAR file. Extract the webapp1 WAR file from the EAR file to the deploy directory, and delete the EAR file. Start the JBoss server, and invoke userregistration.js with the URL, http://localhost:8080/webapp1/userregistration.jsp.

Test the application by specifying a value in the User ID field for a new user ID. The value is modified with each new keystroke made in the User ID field, which displays a validation message. For instance, if a valid ID is specified, the validation message "User ID is valid" displays (see Figure 4).

Author's Note: Single-character user IDs are not used typically in validation applications. The business logic of what is and what is not a valid user ID can be specified on the server side. In addition to testing if a user ID entry has been specified already in the database, additional business logic can be added to check the length of the user ID and whether or not it starts with a particular character.

If you enter a user ID that is defined already in the database, the validation message "User ID is not valid" displays because a duplicate ID cannot be created (see Figure 5).

Figure 4. Valid ID: Each keystroke that modifies the value in the User ID field displays a message indicating whether the entry is valid.

Figure 5. Not Valid: Entering an existing value in the User ID field produces a not valid message for the value, since a dupliate ID cannot be created.

For a valid user ID, specify a password and click the Submit button to create the user ID, which will also reset the form's fields. If the same user ID, which now exists in the database, is specified again, the validation message "User ID is not valid" will display.

As you can see, DWR can be employed to generate JavaScript that corresponds to Java class methods that provide a useful callback feature, which takes advantage of AJAX to return data from the server and update web pages with the server's response. DWR may be integrated with other technologies such as Struts, Spring, JavaServer Faces, and Hibernate. A limitation of DWR is that the server-side application is required to be Java based. According to an Ajaxian.com survey, DWR is used by about 12 percent of AJAX developers.

Deepak Vohra is an O'Reilly technical reviewer, who reviewed the book WebLogic: The Definitive Guide. He's also a NuBean consultant and web developer, and is a Sun Certified Java 1.4 Programmer and Sun Certified Web Component Developer for J2EE.