Adding Ajax Behavior to the Displaytag Library
The JSP custom tag library Displaytag is very good at one thing - rendering HTML tables including links for paging, sorting, and data export to different formats (CSV, Excel, XML). This is very useful for building JSP views but its value is diminished on pages with Ajax behavior because each of the generated page and sort links cause the entire page to be reloaded.
You can use AjaxTags - another JSP custom tag library to make a Displaytag table re-render itself through an AJAX request and that works fine but eventually you might outgrow the approach of wrapping JavaScript code with JSP custom tags and may want to gain further control of client-side behavior. Furthermore AjaxTags requires use of the Prototype JavaScript library, which may or may not suite your deployment scenario.
Actually adding AJAX behavior to a Displaytag table is not that difficult. The code shown below uses the Dojo toolkit but the demonstrated technique can be implemented with any of the other JavaScript toolkits that have remoting capabilities. This is what you need to:
- Add a div tag around the Displaytag table.
- Declare the JavaScript function shown below and pass the div id to it.
function ajaxifyDisplayTag(targetId) {
var onclickHandler =
function (event) {
event.preventDefault();
dojo.xhrGet({
url: event.target.href,
load: function(data){
dojo.byId(targetId).innerHTML = data;
dojo.parser.parse(dojo.byId(targetId));
ajaxifyDisplayTag(targetId);
},
error: function(data){
alert("HXR Error in ajaxifyDisplayTag" + data);
},
});
};
dojo.forEach(
dojo.query('a', dojo.byId(targetId)),
function(aTag) {
console.debug('Set onclick handler for ' + aTag);
dojo.connect(aTag, 'onclick', onclickHandler);
}
);
}
That’s it!
In short what the above function does is it finds every hyperlink within the specified div tag and connects a pre-defined handler to its onclick event. The handler prevents the actual event from taking place and instead fires an AJAX request to the same URL. The returned data is then used to replace the content of the target div tag. Since the returned HTML content is also a Displaytag table we need to invoke the above function on the returned HTML content to ensure its links are connected to our onclick handler.
Of course if your AJAX toolkit already has a data grid widget then you don’t need any of the above. Dojo users are about to get one very soon as part of Dojo the 1.0 release.