devxlogo

Put Some Ajax4JSF Magic into Data Validation

Put Some Ajax4JSF Magic into Data Validation

he Asynchronous JavaScript and XML (AJAX) technology is notorious for making the user experience in web browsers more efficient, dynamic, and enjoyable and can minimize bandwidth usage. AJAX is based on JavaScript, the Document Object Model (DOM), and XMLHttpRequest, and it is used as a web technique for transferring XML between a browser and a server dynamically without posting a web page to the server.

The “asynchronous” in AJAX implies that the processing of the web page continues while XMLHttpRequest is processed on the server and a response is returned to the browser client. AJAX has a lot of applications such as an autocompletion feature that updates a form with corresponding, existing information when an entry is made in one field; dynamic form validation; and periodic refreshing of page sections or areas, which doesn’t require reloading the entire web page.

The JavaServer Faces (JSF) technology provides a set of components for developing user interfaces (UIs) that are the front ends for Java 2 Platform, Enterprise Edition (J2EE) applications. There is an open source framework, Ajax4JSF, that is available for adding AJAX functionality to JSF applications without requiring any JavaScript.

Ajax4JSF provides a component library that you can use to give a JSF page AJAX functionality across the entire page. It supports action and value change listeners and server-side validation and conversion facilities of the JSF framework. Ajax4JSF also supports managing static and dynamic resources, such as images and cascading style sheets (CSSs) and the Facelets framework. To use Ajax4JSF, you need to have these tools installed:

  • JDK 1.4?1.6
  • JSF 1.1 or 1.2
  • A J2EE application server, such as WebSphere 5.1?6, WebLogic 8.1?9.0, or Oracle OC4J 10.1.3
  • A browser that supports XMLHttpRequest, such as Internet Explorer 6 or later or Netscape Navigator 6 or later.

An event on the page invokes an AJAX request, and specified regions of the page are updated with the AJAX response.

Now take a closer look at the Ajax4JSF framework. The Ajax filter is registered in the web.xml file and distinguishes between a JSF request and an AJAX request. In a JSF request the complete JSF page is synchronized with the JSF component tree, while in an AJAX request only the AJAX region, specified by is updated with the AJAX response.

AJAX action components?AjaxCommandButton, AjaxCommandLink, and AjaxSupport?are used to send an AJAX request from the browser to the server.

An Ajax container is an area on a JSF page that is to be decoded during an AJAX request and updated with the AJAX response. The JavaScript engine runs on the client side and updates the different regions of a JSF page with the AJAX response.

Ajax4JSF provides a component library to implement AJAX functionality in JSF. Some of the commonly used components are listed in Table 1.

Table 1. Ajax4JSF Components

ComponentDescriptionAttributes
This component specifies an area that is decoded in an AJAX request; however, components out of the region may be updated. The region defined by f:view is the default region.renderRegionOnly ? If set to TRUE?the default value?the region only is updated with the response.
rendered ? If set to FALSE the component is not rendered.
binding ? Component binding.
ajaxListener ? Method binding that represents a public method that returns void and accepts an AjaxEvent.
This component adds AJAX support to a JSF component and generates an AJAX request on a specified event.actionListener ? Specifies method binding for a public method that returns void and accepts an ActionEvent.
action ? Specifies a method binding for a backing bean method that is invoked after the specified event and before components are re-rendered with the AJAX response.
oncomplete ? JavaScript code to invoke after an AJAX request is completed.
reRender ? Specifies a comma-separated list of component IDs that are updated with the AJAX response.
requestDelay ? Specifies the delay in number of milliseconds (ms) before sending an AJAX request.
event ? A JavaScript event that initiates an AJAX request.
binding ? Component binding.
This component sends periodical AJAX requests at a specified frequency (ms) and updates the page with the response.interval ? Specifies the interval in milliseconds (ms) after which an AJAX request is sent?the default value is 1000 ms (1 second).
actionListener, action, oncomplete, reRender, binding ? Same as for .
This component provides a link that submits a form with AJAX.reRender ? Specifies component IDs that are updated with an AJAX response.
actionListener, oncomplete, action, requestDelay, binding ? Same as for .
This component provides a command button for using AJAX to submit a form.reRender, actionListener, oncomplete, action, requestDelay, binding ? Same as for .
This component provides component grouping in the output area that is updated with an AJAX response. The page area specified by this component may be updated in addition to the components specified in the reRender attribute of a component that initiates an AJAX request.layout ? Specifies HTML layout for generated markup; a value of block generates a

element and a value of inline generates a element.
style ? Specifies a CSS.
ajaxRendered ? Specifies if the component is to be updated in addition to the components updated with reRender.
This component generates multimedia output.mimeType ? The mime-type of the generated content?for example, image/jpeg.
This component provides a form that submits with AJAX.reRender, oncomplete, requestDelay, binding
Generates a pop-up for client-side debug information when an AJAX request is sent.level-Log level ? Values may be FATAL, ERROR, WARN, INFO, DEBUG, or ALL.
width ? Specifies the width of the pop-up.
height ? Specifies the height of the pop-up.

Setting the Stage for Dynamic Validation
You can employ JSF UI components and the Ajax4JSF framework to develop an application that performs dynamic validation as a user enters data. The form acts as an interface for creating catalog entries that are stored in a database table. Each catalog entry has a unique field, called Catalog ID, and for each record there are fields for journal title, publisher, edition, article title, and author.

You can use the AJAX web technique to verify dynamically whether or not an ID value is valid. To perform this kind of validation without AJAX, the complete form would need to be posted to the server to check if a specific ID value exists. If the specified ID value is already in the database, and therefore “invalid” to use as a new ID value, the form would have to be resubmitted with another ID value.

By using AJAX the ID value can be “validated” dynamically as the value is typed in the Catalog ID field. In the example discussed here, catalog records are stored in an Oracle database; therefore, be sure to install Oracle Database 10g?including the sample schema?and create a database instance called ORCL, if you are following along. You can use this SQL script create a database table:

CREATE TABLE OE.Catalog(CatalogID VARCHAR(25)   PRIMARY KEY, Journal VARCHAR(25), Publisher VARCHAR(25),   Edition VARCHAR(25), Title Varchar(255), Author Varchar(25));INSERT INTO OE.Catalog VALUES('catalog1', 'Oracle Magazine',   'Oracle Publishing', 'July-August 2006',   'Evolving Grid Management', 'David Baum');INSERT INTO OE.Catalog VALUES('catalog2', 'Oracle Magazine',   'Oracle Publishing', 'July-August 2005',  'Tuning Undo Tablespace', 'Kimberly Floss');

Installing JDeveloper 10.1.3.2 is also recommended. This version supports JSF 1.1. Then download and extract the Ajax4JSF binary distribution ZIP file: ajax4jsf-1.0.6-binary.zip.

Now you are set to create a JSF application and use the Ajax4JSF framework to add AJAX functionality to it. Your JSF application will consist of a simple input form for a catalog record. As mentioned previously, the form requires a unique Catalog ID field, and the value it receives is validated dynamically on the server. A message displays to indicate the validity status of the ID value. Begin by creating a new application that will be added to the Applications Navigator along with a project:

  1. Select File–>New to create a JDeveloper application in the New Gallery dialog.
  2. Select the General node in the Categories pane, select Application in the Items pane, and click OK.
  3. Specify an application name, and click OK.
  4. Specify a project name.

Next, you’ll need to create a JSF page:

  1. Select File–>New, and select Web Tier–>JSF.
  2. Select JSF JSP, and click OK.
  3. Click Next in the Create JSF JSP Wizard.
  4. Select J2EE 1.4 in the Web Application frame, and click Next.
  5. Specify a file name, input.jsp, and click Next.
  6. Select Automatically Expose UI Components in a New Managed Bean in the Component Binding frame, and click Next.
  7. Click Next in the next frame, as the JSF Core 1.0 and JSF HTML 1.0 libraries are selected by default.
  8. Select the default HTML Options, and click Next.
  9. Click Finish.

Completing this procedure adds the input.jsp file to the AjaxJSF project.

Next, add a JSF JSP page named catalog.jsp that is to be displayed if a catalog entry is created without an error. Also, create a JSF JSP page named error.jsp that is to be displayed if an error does occur as an entry is being created. Be sure to select the default options in the Create JSF JSP Wizard for both catalog.jsp and error.jsp.


Figure 1. Project Libraries: Project libraries for the Ajax4JSF project are available in the Ajax4JSF binary distribution.

Figure 2. Structure: The Applications Navigator area shows the hierarchical directory structure of the AjaxJSF application.

Select the Do Not Automatically Expose UI Components in a Managed Bean option in the Component Binding frame. You will also need to add the lib/Ajax4jsf.jar and lib/oscache-2.3.2.jar files from the Ajax4JSF binary distribution to the project. The project libraries for the Ajax4JSF project are shown in Figure 1.

Copy the JAR files ajax4jsf.jar and oscache-2.3.2.jar from the lib directory of the Ajax4JSF binary distribution to the WEB-INF/lib directory of the AjaxJSF application. The directory structure of the AjaxJSF application is shown in Figure 2. Preparing for Input

Now you can create an input form using JSF components. Begin by adding a Panel Grid component to the input.jsp page from the JSF HTML component library. Click Next in the Create PanelGrid Wizard. Select Create empty panel grid and specify 2 for the number of columns in the PanelGrid Options frame, and then click Finish. The components that will be added to the panel grid will be arranged in two columns.

Add an Output Label and Input Text component from the component palette in the panel grid. Similarly, add five more Output Label and Input Text components, add a Command Button component to the panel grid that will be used for submitting the form, and add an Output Text component to the panel grid for displaying a validation message that will indicate whether an ID value is valid (see Figure 3). Also specify values for the output labels and the command button components in the Property Inspector area.


Figure 3. Create a Form: Use the JDeveloper IDE’s component palette to add five Output Label and Input Text components, a Command Button component, and an Output Text component to the panel grid.

At this point you need to create a JDBC connection with the Oracle database. To create this connection right-click the Database node in the Connections area, and select New Database Connection. Click Next when the Create Database Connection Wizard opens. Specify a connection name, and select the Connection Type as Oracle JDBC in the Type frame, and click Next.

For this example specify OE for both the username and password in the Authentication frame, and click Next. Then select the default connection settings in the Connection frame, and click Next. Click Test Connection in the Test frame to test the connection, and click Finish. You will see that a connection is added to the Connections area.

Add a resource-ref element to the web.xml file for the Oracle data source, and also add an ajax4jsf filter and filter mapping to web.xml. Be sure to also specify a listener class. The web.xml file is shown in Listing 1.

Next, you want to modify the JSF faces-config.xml configuration file. Add a navigation rule for navigating to the catalog.jsp page if a catalog entry gets created, and for navigating to the error.jsp page:

      backing_input    ajaxjsf.backing.Input    request            /input.jsp              catalog        /catalog.jsp                    error        /error.jsp        

Send a Request
To try out the application send an AJAX request from the JSF JSP page, input.jsp, using the Ajax4JSF framework. Add a element to the Catalog ID field. Use the event attribute to specify the event that initiates an AJAX request, and then specify a inputText_action() backing bean method to invoke using the action attribute when an AJAX request is sent. Use the reRender attribute to specify the components that are to be updated with the AJAX response. The h:inputText element for the Catalog ID field is:

  

To use the Ajax4JSF component library, add this taglib directive to the JSF JSP page, input.jsp (see Listing 2):

<%@ taglib uri="https://ajax4jsf.dev.java.net/ajax"   prefix="a4j"%>

To create a catalog entry when the form is submitted by clicking the command button, add an action attribute to the command button to invoke the commandButton_action() method when the command button is clicked. Here is the command button element:

Modify catalog.jsp to output a message that a catalog entry has been created, and modify error.jsp to output a message that an error has been generated in updating the database.

The value entered in the Catalog ID field is validated on the server side where the database table Catalog resides. If the ID value already exists in the database, the message, “Catalog Id is not valid” displays on the input form to tell the user that the number already exists and therefore the entry is not “valid” as a new ID number. If the entry in the Catalog ID field doesn’t already exist in the database, the validation message, “Catalog Id is valid” displays on the input form. The business logic that defines a valid ID value can be specified on the server side.

The inputText_action() method is invoked when a value is specified in the Catalog ID field. An AJAX request is sent with each modification in the Catalog ID field?that is, each time a new character is typed. Obtain a connection with the Oracle database in the inputText_action() method using the Oracle data source configured in JDeveloper:

 InitialContext initialContext = new InitialContext();  javax.sql.DataSource ds =   (javax.sql.DataSource)initialContext.lookup(  "java:comp/env/jdbc/OracleDBConnectionDS");  java.sql.Connection connection = ds.getConnection();

Run a Statement object in a SQL statement:

 Statement stmt = connection.createStatement(  ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);

You can obtain the Catalog ID value that is specified in the form and create a SQL query to run in the Oracle database:

String catalogID = (String)inputText1.getValue();  String query = "SELECT * from Catalog WHERE CATALOGID=" + "'" +   catalogID + "'";

Run the SQL query and obtain a result set:

rs = stmt.executeQuery(query);

If the result set isn’t empty, set the validation message to “Catalog Id is not valid,” set the field values, and disable the command button:

if (rs.next()) {  inputText2.setValue(rs.getString(2));  inputText3.setValue(rs.getString(3));  inputText4.setValue(rs.getString(4));  inputText5.setValue(rs.getString(5));  inputText6.setValue(rs.getString(6));  outputText1.setValue(new String("Catalog Id is not Valid"));  commandButton1.setDisabled(true);  }

If the result set is empty, implying that the ID value specified in the input form is not already in the database, set the validation message to, “Catalog Id is valid,” set the field values to empty Strings, and enable the Submit button:

else {  inputText2.setValue(new String());  inputText3.setValue(new String());  inputText4.setValue(new String());  inputText5.setValue(new String());  inputText6.setValue(new String());  outputText1.setValue(new String("Catalog Id is Valid"));  commandButton1.setDisabled(false);  }

If the ID value is valid?the value in the field doesn’t exist already in the database?retrieve the form field values, obtain a connection with the database, and create a new catalog entry. The backing bean class, Input.java, is shown in Listing 3.

Process the Response
Now you can run the application to test validating the ID values you specify in the form against the data in the Catalog database table. If the ID value you enter already exists, the application interprets the entry as invalid, a message indicating that result displays, the other form field values for the existing record display, and the Submit button is disabled.

If the ID value you enter doesn’t already exist in the database table, the application interprets it as valid, a message indicating that result displays, the other form fields are set to empty String values, and the Submit button is enabled.

For a valid ID, you can create a catalog entry and use the Submit button to store it. The JSF components set in the reRender attribute of the tag specify the components to be updated with the AJAX response.

Now run the JSF page by right-clicking input.jsp and selecting Run. Specify a value for the Catalog ID field. An AJAX request is sent with each modification to the field (as each character is typed), and the validation message indicating that the ID number is unique (valid) displays.

Next, specify an ID value that is already in the database?for example, catalog2. Notice that the message “Catalog Id is not valid” appears. Because the value exists in the database, autocompletion fills out the form field with values and the Submit button is disabled.

As you can see, the Ajax4JSF component library adds AJAX functionality to JSF applications, which precludes requiring JavaScript code to add the AJAX functionality.

See also  Are Deceased Social Media Accounts Outnumbering the Living?
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