AJAX4JSF is library of JSF components which can be used to easily add AJAX capabilities to JSF web applications. AJAX4JSF is available as part of the Richfaces component library.
For this example, let us consider a simple goal of listing a set of products or services based on the category chosen by the user. A combo box is presented to the user, where he can choose between “Products” and “Services”. Based on his choice a list of products or services is retrieved from the server and displayed.
The user can also hit “Ctrl + 1” to list all products and “Ctrl + 2” to list all services, instead of choosing from the combo box.
While in real world scenarios, the list of products/services will have to retrieved from a DB, to keep the example simple, we just swap between 2 predefined lists of Strings.
<a4j:support>
tag is used to send an AJAX request to the server whenever the
combo box selection changes.
<a4j:support event="onchange" action="#{dataLoader.updateCurrentData}"
rerender="currentItemsTable">
</a4j:support>
Providing shortcut keys involves two steps.
<a4j:jsFunction>
tag to define a Javascript function which takes the
category as parameter.This tag simplifies the client side process of initiating AJAX request from Javascript. The value specified for its name attribute is used as the name of the Javascript function generated. It also takes the JSF action to be invoked and the region of page to be re-rendered after the AJAX request as attributes.
<a4j:actionparam>
tag can be used to define the parameters to be accepted by
the generated JS frunction and the managed bean property to which they are to
be assigned. In our case the key pressed is passed as parameter to the
generated JS function, updateData()
.
<a4j:jsFunction name="updateData" action="#{dataLoader.updateCurrentData}"
reRender="currentItemsTable">
<a4j:actionparam name="choice" assignTo="#{dataLoader.currentChoice}" />
</a4j:jsFunction>
This fragment of Javascript is used to check for keystrokes and invoke the generated JS function with appropriate parameter.
var ctrlPressed;
document.onkeydown = function(e) {
var keyCode;
if (window.event)
keyCode = window.event.keyCode;
else if (e.which)
keyCode = e.which;
if (keyCode == 17)
ctrlPressed = true;
if (ctrlPressed) {
switch (keyCode) {
case 49:
updateData(1);
break;
case 50:
updateData(2);
break;
}
}
}
document.onkeyup = function(e) {
var keyCode;
if (window.event)
keyCode = window.event.keyCode;
else if (e.which)
keyCode = e.which;
if (keyCode == 17)
ctrlPressed = false;
}
All opinions are my own. Copyright 2005 Chandra Sekar S.