devxlogo

Apply DWR to Data Validation in an AJAX Application

Apply DWR to Data Validation in an AJAX Application

irect Web Remoting (DWR) is a Java open source library for developing AJAX applications that consists of two components: JavaScript running in the browser that sends requests and dynamically updates the web page with the response, and a servlet running on the server that processes requests and sends responses back to the browser. Remoting in DWR implies that Java class methods are remoted as JavaScript functions in the browser. DWR dynamically generates JavaScript corresponding to Java classes, and the JavaScript may be run in the browser just as any other JavaScript class library.

The generated JavaScript functions that correspond to Java class methods have a callback function as one of the parameters. The remote methods are invoked in the browser using the callback function, and the request is sent to the server using AJAX. When the request is complete AJAX is used to return a response to the browser. The callback function specified in the remote method is invoked with the data returned from the server, and the web page may be updated with the server response.

Download the DWR 1.1.4 JAR file, dwr.jar. Most browsers support DWR, and the application example described here will employ Microsoft Internet Explorer 6. DWR requires the Java Developer Kit (JDK) 1.3 or later and a servlet container that supports servlet specification 2.2 or later. Install a JDK if one is not installed already. JDK 1.5.0_10 was used for the application example discussed here.

DWR has been tested on these web servers: Tomcat, WebLogic, WebSphere, JBoss, Jetty, Resin, Sun ONE, and Glassfish. For this application use JBoss 4.05. Install JBoss 4.x, if it’s not installed already. This DWR application will also use the MySQL database; installing MySQL 5.0 is therefore recommended. Create a database table named UserTable in the MySQL database using this script:

CREATE TABLE UserTable(userid VARCHAR(25) PRIMARY KEY, password VARCHAR(25));INSERT INTO UserTable VALUES('dvohra', 'ajaxdwr');INSERT INTO UserTable VALUES('jsmith', 'smith');

Configure JBoss with MySQL by copying the mysql-ds.xml file from the JBossjboss-4.0.5.GAdocsexamplesjca directory to the JBossjboss-4.0.5.GAserverdefaultdeploy directory. The MySQL datasource is specified as MySqlDS in the mysql-ds.xml file. Specify the connection URL and driver class:

jdbc:mysql://localhost:3306/testcom.mysql.jdbc.Driver

A password is not required for the root user. Specify the user-name and password this way:

root  

Download the MySQL JDBC driver JAR file, mysql-connector-java-5.0.4-bin.jar, and copy it to the jboss-4.0.5.GAserverdefaultlib directory. For this discussion the DWR web application example was developed in the JDeveloper IDE. You can download the JDeveloper 10.1.3.2 ZIP file, and extract it to a separate directory to install it.

Creating a DWR Application
The AJAX registration form validation application will validate a user ID through a form for creating a user registration with a unique user ID. If the specified user ID isn't in the UserTable database table, the message "User ID is valid" displays, and a new user registration entry can be created. If the user ID is in the database already, the validation message "User ID is not Valid" displays.

  1. Select File-->New to create a JDeveloper application and project.
  2. Select General-->Application in the New Gallery window.
  3. Specify an application name?DWRApp, for example?and click OK.
  4. Specify a project name?DWR, for example?and click OK.
  5. Select File-->New to create a JavaServer Page (JSP).
  6. Select Web Tier-->JSP-->JSP in the New Gallery window, and click OK to start the Create JSP Wizard.
  7. Follow the wizard's steps to select "web application version servlet 2.4."
  8. Specify the file name, userregistration.jsp.
  9. Select the default Error Page Options, and select the default tag libraries, which are none.
  10. Select the default HTML Options.

When you click Finish the newly created JSP can be used to specify an HTML form and JavaScript functions, which will be discussed shortly.

The next step is to create a Java class that is to be remoted with DWR-generated JavaScript. Select File-->New, select General-->Java Class in the New Gallery window, and click OK. Specify the Java class name, UserRegistration, and a package name, dwr, and then click OK to add the Java class to the JDeveloper application.

You need to add a DWR configuration file, dwr.xml, to the WEB-INF directory. Select the WEB-INF folder in the Applications Navigator, and select File-->New. Select General-->XML-->XML Document in the New Gallery window, and click OK. Specify the file name as dwr.xml, and click OK to create the file. Create a directory named lib in the WEB-INF directory, and copy the dwr.jar file to it (see Figure 1).

Now configure a connection with the JBoss application server. Select the Connections tab, right-click the Application Server node, and select Create New Application Server Connection to start the Create Application Server Connection Wizard. Click Next; specify the connection name, JBossConnection; select Connection Type as JBoss 4.x, and click Next. In the JBoss Directory window specify the deploy directory?for example, Jbossjboss-4.0.5.GAserverdefaultdeploy?and click Next. When you click Finish, a JBoss application server connection is created (see Figure 2).

Figure 1. DWR Application Structure: The directory structure for the DWR application setup should look like this.
Figure 2. JBoss Connection: The Create Application Server Connection Wizard lets you establish a connection with the JBoss application server.

Now you can modify the DWR application files. Use the dwr.xml file to specify creators and converters. Create the dwr.xml file by basing it on the Document Type Definition (DTD) for it. Its root element is dwr. Use the creators to create JavaScript corresponding to Java classes, and use converters to convert between Java datatypes on the server side and JavaScript datatypes on the client side. These datatypes and the date converter are enabled by default; therefore, you won't be using a converter:

  • boolean
  • byte
  • short
  • int
  • long
  • float
  • double
  • char
  • java.lang.Boolean
  • java.lang.Byte
  • java.lang.Short
  • java.lang.Integer
  • java.lang.Long
  • java.lang.Float
  • java.lang.Double
  • java.lang.Character
  • java.math.BigInteger
  • java.math.BigDecimal
  • java.lang.String

Classes that are to be allowed access from JavaScript are specified in the allow element. The create element specifies the classes that are to be remoted in JavaScript:

Common Creators
The create element has the required attributes creator and javascript and an optional attribute, scope:

The creator attribute specifies which creator is used to instantiate the Java class. The most commonly used creator is new. The javascript attribute specifies the JavaScript class library that is created from the Java class, and the scope attribute specifies the scope in which the JavaBean is available: application, page, session, and request. The default value of the optional scope attribute is page. Specify the create element for the application example:

        

The create element has zero or more each of param, include, exclude, and auth subelements:

The param element specifies configuration for different types of creators. The new creator requires the type of object on which to invoke new. For example, to invoke new on the Java class UserRegistration, use a param element:

The include element specifies which methods are to be included for remoting in JavaScript, and the default is all methods. The exclude element specifies which Java class methods are excluded for remoting. By default, none of the methods are excluded. Here is the dwr.xml for the DWR application example:

                  

Copy dwr.xml to the JDeveloper project. At this point you also need to modify the web.xml deployment descriptor to specify the DWRServlet (see Listing 1). Copy web.xml to the JDeveloper project.

The Java class, UserRegistration.java, to be remoted specifies two methods: validate(String userId) and updateUserTable(String userId, String password). The validate() method validates a user ID specified in the user registration entry form. Its return type is boolean. Using the datasource configured in JBoss, a connection with the MySQL database is first obtained in the validate() method:

InitialContext initialContext = new InitialContext();  javax.sql.DataSource ds = (javax.sql.DataSource)initialContext.lookup("java:MySqlDS");  java.sql.Connection conn = ds.getConnection();

A SQL query is run in the MySQL database using the user ID specified in the user registration entry form:

Statement stmt = conn.createStatement();  String query = "SELECT * from UserTable WHERE userId=" + "'" + userId + "'";      ResultSet rs = stmt.executeQuery(query);

If the result set isn't empty, the user ID specified is defined already in the database and is therefore not valid. If the result set has data, create a boolean variable with the value false:

if (rs.next()) {  valid  = false;    return valid;  }

If the result set is empty, the user ID is valid, and a new user registration entry can be created. Return true if the result set is empty. If the user ID is valid, invoke the updateUserTable() method to create a new user entry. Listing 2 shows the UserRegistration.java class. Copy UserRegistration.java to the JDeveloper project. 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

FunctionDescription
$()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():

...
User ID:

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:

function  validateUserId(){  var userId = DWRUtil.getValue("userId");  UserRegistration.validate(getValMessage, userId);  }

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.

See also  Custom Java Web Development - The Heartbeat of Modern Web Development
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist