Using AJAX with AjaxTags

This article was originally published in VSJ, which is now part of Developer Fusion.
Asynchronous JavaScript and XML (AJAX) is a web technique used to transfer data between a client script running on a web page and a server without posting the web page to the server. Thus, AJAX provides dynamic interaction between a client and a server that can be used for autocompletion, form validation, and periodical refreshes of a web page. AjaxTags is a tag library for implementing the AJAX web technique in a JSP page. JavaScript code to create an XMLHttpRequest object, send a request and process the response is not required, because the AJAX web technique is implemented by AjaxTags.

Preliminary Setup

We need to install a web server to develop the AjaxTags application. JDeveloper includes an embedded OC4J server so install JDeveloper 10.1.3. Also install the Oracle 10g database. Create a database instance, ORCL, for example and install the sample schemas. Download the AjaxTags Binary zip file ajaxtags-1.2-beta2-bin.zip. Extract the zip file to a directory, C:\ajaxtags-1.2-beta2 directory for example.

Next, create an Oracle database table with the following SQL script.

CREATE TABLE OE.Catalog(
	CatalogId VARCHAR(25) PRIMARY KEY,
	Journal VARCHAR(25),
	Publisher VARCHAR(25),
	Edition VARCHAR(25),
	Title VARCHAR(45),
	Author VARCHAR(25));
INSERT INTO OE.Catalog VALUES(
	‘catalog1’, ‘Oracle Magazine’,
	‘Oracle Publishing’,’Nov-Dec 2004’,
	‘Database Resource Manager’,
	‘Kimberly Floss’);
INSERT INTO OE.Catalog VALUES(
	‘catalog2’, ‘Oracle Magazine’,
	‘Oracle Publishing’,
		‘Nov-Dec 2004’,
	‘From ADF UIX to JSF’,
	‘Jonas Jacobi’);
INSERT INTO OE.Catalog VALUES(
	‘catalog3’, ‘Oracle Magazine’,
	‘Oracle Publishing’,
		‘March-April 2005’,
	‘Starting with Oracle ADF ‘,
	‘Steve Muench’);
Then create a new application and project with File>New. In the New Gallery frame select General>Applications in Categories and Application in Items. A new project gets added as shown in Figure 1.

Figure 1
Figure 1: AjaxTags Project

Next, create a JDBC connection in JDeveloper with Oracle database. Select the Connections tab. Right-click on the Database node and select New Database Connection to create a new database connection with Oracle database. A DBConnection1 connection in Connections-Navigator is available as a jndi resource jdbc/DBConnection1DS.

Overview of AjaxTags

AjaxTags provides various tags to implement the AJAX functionality. Some of the commonly used tags are discussed in Table 1.

Table 1: AjaxTags Tags
Tag Name Description Parameters
ajax:anchors Converts any anchor tags (<a></a> tags) to be AJAX enabled. target (required) – Target region on the page where the AJAX response is output.
ajaxFlag – A boolean flag to indicate if the rest of the page is to be ignored in an AJAX call (default value is false).
ajax:autocomplete Retrieves a list of probable values from the server, for incomplete text in an input field, and displays them in a dropdown beneath the input text field. The input text field gets autocompleted when a value is selected from the list. baseUrl (required) – Server side url that processes the AJAX request and returns a list of values.
source (required) – id of the text field in which the search string is specified. Value of autocomplete selection gets specified in this field.
target (required) – id of the text field in which value of autocomplete selection gets specified. The target id may be set to the same value as the source id if a second field is not required to be filled with the autocomplete selection.
parameters (required) – A list of parameters sent to the server.
ajax:htmlContent Fills a region on the page with HTML content returned by the server. Tag should be after the web form. baseUrl (required) – Server side url that processes the AJAX request.
source – id of the element to which the event is attached.
sourceClass – CSS class name to which event is attached. Either source or sourceClass is required.
target (required) – id of div tag or other element that is filled with the HTML response.
parameters (required) – A list of parameters sent to the server.
ajax:select Retrieves a list of values from the server and displays them in a HTML select list. Tag is required to appear after the web form. baseUrl (required) – Server side url that processes the AJAX request.
source – id of the select field to which the event is attached.
target (required) – id of the select field that is filled with the AJAX response.
parameters (required) – A list of parameters sent to the server.
ajax:updateField Updates one or more form fields based on value of another field. baseUrl (required) – Server side url that processes the AJAX request.
source – Form field whose value is sent to the server as a parameter.
target (required) – A list of form field IDs that are filled with the AJAX response.
action (required) – id of button or image tag that sends the onclick event.

Installing AjaxTags

Now to create an AjaxTags application in JDeveloper. To the AjaxTags project add a JSP page, input.jsp, with Web Tier>JSP in the New Gallery frame. The HMTL code of input.jsp starts off in the usual way:
<%@ taglib uri=”http://ajaxtags.org/
	tags/ajax” prefix=”ajax” %>
<script type=”text/javascript”
	src=”prototype-1.4.0.js”></script>
<script type=”text/javascript”
	src=”scriptaculous.js”></script>
<script type=”text/javascript”
	src=”overlibmws.js”></script>
<script type=”text/javascript”
	src=”ajaxtags.js”></script>
<html>
	<head>
	<title>AJAXTags</title>
	</head>
<body>
The body of the page consists of a form containing a table:
<h1>Form for Catalog Entry</h1>
<form name=”validationForm”
	action=”formservlet” method=”post”>
	<table>
		<tr>
			<td>Catalog Id:</td><td>
			<select id=”catalogId”
				name=”catalogId”>
				<option
			value=”Select Catalog Id”>
					Select Catalog
					Id</option>
				<option
					value=”catalog1”>
					catalog1</option>
				<option
					value=”catalog2”>
					catalog2</option>
				<option
					value=”catalog3”>
					catalog3</option>
				<option
					value=”catalog4”>
					catalog4</option>
			</select></td>
			<td><div
	id=”validationMessage”></div></td>
		</tr>
The remainder of the table simply lists the fields:
		<tr><td>Journal:</td>
			<td><input type=”text”
				size=”20” id=”journal”
				name=”journal”
				autocomplete=”off”>
		</td></tr>
		<tr><td>Publisher:</td>
			<td><input type=”text”
				size=”20” id=”publisher”
				name=”publisher”
				autocomplete=”off”>
		</td></tr>
		<tr><td>Edition:</td>
			<td><input type=”text”
				size=”20” id=”edition”
				name=”edition”
				autocomplete=”off”>
		</td></tr>
		<tr><td>Title:</td>
			<td><input type=”text”
				size=”20” id=”title”
				name=”title”
				autocomplete=”off”>
		</td></tr>
		<tr><td>Author:</td>
			<td><input type=”text”
				size=”20” id=”author”
				name=”author”
				autocomplete=”off”>
		</td></tr>
			<tr>
			<td>
				<input type=”submit”
				value=”Create Catalog”
					id=”submitForm”
					name=”submitForm”>
			</td>
			<td>
				<button id=”updateForm”>
				Update Fields</button>
			</td>
		</tr>
	</table>
</form>
Finally we have the two AJAX tags:
<ajax:htmlContent
	baseUrl=”formservlet”
	source=”catalogId”
	target=”validationMessage”
parameters=”catalogId={catalogId}” />
<ajax:updateField
	baseUrl=”formupdateservlet”
	source=”catalogId”
	target=”journal,publisher,
		edition,title,author”
	action=”updateForm”
	parser=”new ResponseXmlParser()”
parameters=”catalogId={catalogId}” />
</body>
</html>
Similarly, add JSP the error.jsp to handle the error message:
<html>
	<head></head>
	<body>
		<%out.println(“Error in
		updating Database”);%>
	</body>
</html>
…and catalog.jsp, to handle the success message:
<html>
	<head></head>
	<body>
		<%out.println(
			“Database Updated”);%>
	</body>
</html>
For server side processing add a servlet, FormServlet with Web Tier>Servlets>HTTP Servlet in the New Gallery frame. The code for FormServlet starts off in the usual way with:
package ajaxtags;
import java.io.*;
import java.sql.*;
import javax.naming.InitialContext;
import javax.servlet.*;
import javax.servlet.http.*;
public class FormServlet extends
	HttpServlet {
The doGet method first obtains the value of Catalog Id field to be validated:
public void doGet(HttpServletRequest
	request, HttpServletResponse
	response) throws ServletException,
	IOException {
	try {
		String catalogId =
	request.getParameter(“catalogId”);
		if(catalogId.equals(
			“Select Catalog Id”)){
			response.setContentType(
				“text/html”);
			response.setHeader(
		“Cache-Control”, “no-cache”);
			PrintWriter out =
				response.getWriter();
			out.println(“<p></p>”);
		}
Next we connect to the database and obtain the result set:
		if(!(catalogId.equals(
			“Select Catalog Id”))){
			InitialContext
initialContext = new InitialContext();
			javax.sql.DataSource ds =
				(javax.sql.DataSource)
				initialContext.lookup(
“java:comp/env/jdbc/DBConnection1DS”);
			java.sql.Connection conn =
				ds.getConnection();
			Statement stmt =
				conn.createStatement();
			String query = “SELECT *
				from OE.Catalog
				WHERE CatalogId=” +
				“‘“+ catalogId + “‘“;
				ResultSet rs =
			stmt.executeQuery(query);
Now we have the result set we can set the headers and write the response:
			response.setContentType(
				“text/html”);
			response.setHeader(
		“Cache-Control”, “no-cache”);
			PrintWriter out =
				response.getWriter();
			if (rs.next()) {
				out.println(“<p>Catalog
				Id is not Valid</p>”);
			} else {
				out.println(
		“<p>Catalog Id is Valid</p>”);
			}
		rs.close();
		stmt.close();
		conn.close();
	}
} catch (
	javax.naming.NamingException e) {
	} catch (SQLException e) {
	}
}
The doPost method first obtains a connection to the database:
public void doPost(HttpServletRequest
	request, HttpServletResponse
	response) throws ServletException,
	IOException {
	try {
		InitialContext initialContext =
			new InitialContext();
		javax.sql.DataSource ds =
			(javax.sql.DataSource)
			initialContext.lookup(
“java:comp/env/jdbc/DBConnection1DS”);
			java.sql.Connection conn =
				ds.getConnection();
Then it retrieves the Post parameters:
			String catalogId =
	request.getParameter(“catalogId”);
			String journal =
	request.getParameter(“journal”);
			String publisher =
	request.getParameter(“publisher”);
			String edition =
	request.getParameter(“edition”);
			String title =
	request.getParameter(“title”);
			String author =
		request.getParameter(“author”);
These are used to build and execute a SQL statement:
			Statement stmt =
				conn.createStatement();
			String sql = “INSERT INTO
				Catalog VALUES(“ +
		“\’” + catalogId+ “\’” + “,” +
		“\’” + journal + “\’” + “,” +
“\’”+ publisher + “\’” + “,” +
“\’” + edition + “\’” + “,”+
“\’” + title + “\’” + “,” +
“\’” + author + “\’” + “)”;
				stmt.execute(sql);
			response.sendRedirect(
				“catalog.jsp”);
			stmt.close();
			conn.close();
		} catch (
javax.naming.NamingException e) {
			response.sendRedirect(
				“error.jsp”);
	} catch (SQLException e) {
		response.sendRedirect(
			“error.jsp”);
	}
}
Similarly, add another servlet FormUpdateServlet which starts in the same way:
package ajaxtags;
import java.io.*;
import java.sql.*;
import javax.naming.InitialContext;
import javax.servlet.*;
import javax.servlet.http.*;
import
org.ajaxtags.helpers.AjaxXmlBuilder;
public class FormUpdateServlet extends
	HttpServlet {
The doGet method first obtains the value of the Catalog Id field to be validated and returns null values if it is the “Select Catalog Id” field:
public void doGet(HttpServletRequest
	request, HttpServletResponse
	response) throws ServletException,
	IOException {
	try {
		String catalogId =
	request.getParameter(“catalogId”);
		if(catalogId.equals(
			“Select Catalog Id”)){
			AjaxXmlBuilder builder =
			new AjaxXmlBuilder();
			response.setContentType(
				“text/xml”);
			response.setHeader(
		“Cache-Control”, “no-cache”);
			PrintWriter out =
			response.getWriter();
	builder.addItem(“journal”,null);
	builder.addItem(“publisher”,null);
	builder.addItem(“edition”,null);
	builder.addItem(“title”,null);
	builder.addItem(“author”,null);
	out.println(builder.toString());
		}
For any other value of the Catalog Id field we make the connection to the database and retrieve the result set:
		 if(!(catalogId.equals(
			“Select Catalog Id”))){
			InitialContext
initialContext = new InitialContext();
			javax.sql.DataSource ds =
				(javax.sql.DataSource)
				initialContext.lookup(
“java:comp/env/jdbc/DBConnection1DS”);
			java.sql.Connection conn =
				ds.getConnection();
			Statement stmt =
				conn.createStatement();
			String query = “SELECT *
				from Catalog
				WHERE CatalogId=” + “‘“
				+ catalogId + “‘“;
			ResultSet rs =
				stmt.executeQuery(query);
Now we can write the response and close the connections:
			response.setContentType(
				“text/xml”);
			response.setHeader(
		“Cache-Control”, “no-cache”);
			PrintWriter out =
				response.getWriter();
			if (rs.next()) {
				AjaxXmlBuilder builder =
					new AjaxXmlBuilder();
				String journal=
				rs.getString(“Journal”);
				String publisher=
			rs.getString(“Publisher”);
				String edition=
				rs.getString(“Edition”);
				String title=
				rs.getString(“Title”);
				String author=
				rs.getString(“Author”);
				builder.addItem(
					“journal”,journal);
				builder.addItem(
				“publisher”,publisher);
				builder.addItem(
					“edition”,edition);
				builder.addItem(
					“title”,title);
				builder.addItem(
					“author”,author);
				out.println(
					builder.toString());
			} else {
				AjaxXmlBuilder builder =
					new AjaxXmlBuilder();
				builder.addItem(
					“journal”,null);
				builder.addItem(
					“publisher”,null);
				builder.addItem(
					“edition”,null);
				builder.addItem(
					“title”,null);
				builder.addItem(
					“author”,null);
				out.println(
					builder.toString());
			}
		rs.close();
		stmt.close();
		conn.close();
		}
	} catch (
	javax.naming.NamingException e) {
	} catch (SQLException e) {
	}
}
Add JAR files standard-1.0.6.jar,commons-lang-2.1.jar from the C:/ajaxtags-1.2-beta2/lib directory and ajaxtags-1.2-beta2.jar from the C:/ajaxtags-1.2-beta2/dist directory to the AjaxTags project libraries with Tools>Project Properties. Select Libraries in the Project Properties frame and add the JAR files with the Add Jar/Directory button as shown in Figure 2.

Figure 2
Figure 2: AjaxTags Libraries

Extract ajaxtags.tld from the ajaxtags-1.2-beta2.jar file and copy the ajaxtags.tld file to the WEB-INF directory. Copy JavaScript files ajaxtags.js, overlibmws.js, prototype-1.4.0.js, scriptaculous.js, and controls.js from the C:\ajaxtags-1.2-beta2\js directory to the public_html directory.

The directory structure of the AjaxTags project is shown in Figure 3.

Figure 3
Figure 3: AjaxTags Project Directory Structure

Validating a Form with AjaxTags

We proceed to validate an input form that has a Catalog Id value as one of the inputs. The form is used to create a new catalog entry in the Catalog table in the Oracle database. The Catalog Id value is selected from a list of values. A validation message indicates the validity of the Catalog Id value. The input form uses the AjaxTags taglib. JSP input.jsp is the input form. In input.jsp declare a taglib directive for the AjaxTags taglib.
<%@ taglib
	uri=”http://ajaxtags.org/tags/ajax”
	prefix=”ajax” %>
Specify the JavaScript files for AjaxTags in the input.jsp. JavaScript file prototype.js should be specified before the ajaxtags-1.2.js.
<script type=”text/javascript”
	 src=”prototype-1.4.0.js”></script>
<script type=”text/javascript”
	src=”scriptaculous.js”></script>
<script type=”text/javascript”
	src=”overlibmws.js”></script>
<script type=”text/javascript”
	src=”ajaxtags-1.2.js”></script>
Add a selection list for Catalog Id and fields for Journal, Publisher, Edition, Title, and Author. Also add a div for the validationMessage. We shall use the ajax:htmlContent tag to validate a Catalog Id value. The ajax:htmlContent tag specifies a source attribute that specifies the form element that initiates n AJAX request. The baseUrl attribute specifies the URL to which the AJAX request is sent. The parameters attribute specifies the parameters to be sent with the AJAX request. The target attribute specifies the form element that is to be updated with the response from the server.
<ajax:htmlContent
baseUrl=”formservlet”
source=”catalogId”
target=”validationMessage”
parameters=”catalogId={catalogId}” />
In the example application the catalogId initiates an AJAX request, which gets sent to server URL formservlet with the GET method with the parameter catalogId. The server HTML response updates the content of the validationMessage div. URL formservlet is mapped to FormServlet. In the doGet() method of the FormServlet retrieve the value of the catalogId.
String catalogId =
	request.getParameter(“catalogId”);
Obtain a JDBC connection with Oracle database using the datasource configured in JDeveloper with the database. Retrieve a result set for the Catalog Id. If the result set is empty the Catalog Id value specified in the input form is valid and if the result set is not empty the Catalog Id value is not valid. The response from the server for an AJAX request sent with the ajax:htmlContent tag is required to be HTML. Therefore, set content type of the response to HTML:
response.setContentType(“text/html”);
With rs as the ResultSet output an HTML response that includes instructions about the validity of the Catalog Id value:
if (rs.next()) {
	out.println(
	“<p>Catalog Id is not Valid</p>”);
} else {
	out.println(
		“<p>Catalog Id is Valid</p>”);
}
Next, update the form fields with values for a specified Catalog Id. Add a ajax:updateField tag to update form fields. The baseUrl attribute of the ajax:updateField tag specifies the server URL to which the AJAX request is sent. The source attribute specifies the form field that specifies the parameter to be sent with the AJAX request. The target attribute specifies a comma separated list of form fields that are to be filled with response from the server. The action attribute specifies the ID of the form button or image that initiates an AJAX request. The parser attribute specifies the parser to be used to parse the server response. The default parser is ResponseHtmlParser. If the response is XML, set the parser to ResponseXmlParser. The parameters attribute specifies the list of parameters to be sent to the server.
<ajax:updateField
baseUrl=”formupdateservlet”
source=”catalogId”
target=”journal,publisher,edition,
	title,author”
action=”updateForm”
parser=”new ResponseXmlParser()”
parameters=”catalogId={catalogId}” />
In the example application the baseUrl is formupdateservlet. As formupdateservlet is mapped to FormUpdateServlet the AJAX request is sent to FormUpdateServlet. The source attribute is set to catalogId and the parameters attribute is also set to catalogId, the field value that is sent with the AJAX request. The action attribute is set to updateForm, a button ID in the form. The target attribute is set to journal, publisher, edition,title, author, the form fields that are to be filled with the server resonse. The parser attribute is set to ResponseXmlParser.

In the FormUpdateServlet, the catalogId parameter value is retrieved and a result set obtained from the database table Catalog for the catalogId value. The XML response from the server is constructed with the AjaxXmlBuilder class. The format of the XML response is as follows:

<?xml version=”1.0” encoding=”UTF-8”?>
<ajax-response>
	<response>
		<item>
			<name>Record 1</name>
			<value>1</value>
		</item>
		<item>
			<name>Record 2</name>
			<value>2</value>
		</item>
		<item>
			<name>Record 3</name>
			<value>3</value>
		</item>
	</response>
</ajax-response>
Create an AjaxXmlBuilder object to construct the response and set the response content type to XML:
AjaxXmlBuilder builder =
	new AjaxXmlBuilder();
response.setContentType(“text/xml”);
Obtain the values from the ResultSet object:
String journal=
	rs.getString(“Journal”);
String publisher=
	rs.getString(“Publisher”);
String edition=
	rs.getString(“Edition”);
String title=rs.getString(“Title”);
String author=rs.getString(“Author”);
Add the field values to the AjaxXmlBuilder object:
builder.addItem(“journal”,journal);
builder.addItem(
	“publisher”,publisher);
builder.addItem(“edition”,edition);
builder.addItem(“title”,title);
builder.addItem(“author”,author);
Output the AjaxXmlBuilder XML response:
out.println(builder.toString());
Next, we shall run the AjaxTags application in OC4J server. Right-click on the input.jsp and select Run as shown in Figure 4.

Figure 4
Figure 4: Running AjaxTags Application

Select a Catalog Id value from the selection list as shown in Figure 5.

Figure 5
Figure 5: Selecting a Catalog Id Value

An AJAX request gets sent to the server with the ajax:htmlContent AjaxTags tag. The server returns an HTML response about the validity of the Catalog Id value. As the catalog1 value is already in the database, a validation message gets displayed, “Catalog Id is not Valid” as shown in Figure 6.

Figure 6
Figure 6: Validating Catalog Id

Update the form fields with the Update Fields button. The Update Fields button sends an AJAX request with the ajax:updateField AjaxTags tag. The XML server response gets parsed by the ResponseXmlParser, and the form fields get filled with the response values.

To create a new catalog entry, select a Catalog Id value – catalog4 for example – that is not already in the database. The validation message “Catalog Id is Valid” is displayed and null values get specified. Click on the Create Catalog button to create a catalog entry.

A new catalog entry gets created in the database. If the input.jsp is re-run and the catalog4 value is re-selected a validation message gets displayed, “Catalog Id is not Valid”. Update the form fields with the Update Fields button.

Conclusion

The AjaxTags tag library is an AJAX framework to include the AJAX web technique in a JSP application. With its use the developer is not required to send the AJAX request and process the AJAX response.


Deepak Vohra is a Web developer, a Sun Certified Java Programmer and Sun Certified Web Component Developer based in Canada. He has contributed to various Java publications and web sites, including Java Developer’s Journal, WebLogic Developer’s Journal, XML Journal and Oracle Magazine.

You might also like...

Comments

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“The greatest performance improvement of all is when a system goes from not-working to working.” - John Ousterhout