Sprinkle Some AJAX Magic in Your Struts Web Application Updating the Web Page with the AJAX ResponseSo far, we have looked at the JavaScript to do the AJAX call (listed above) and the Struts
function processStateChange() { if (req.readyState == 4) { // Complete if (req.status == 200) { // OK response //Split the text response into Span elements spanElements = splitTextIntoSpan(req.responseText); //Use these span elements to update the page replaceExistingWithNewHtml(spanElements); } else { alert("Problem with server response:\n " + req.statusText); } } }
function replaceExistingWithNewHtml (newTextElements){ //loop through newTextElements for(var i=newTextElements.length-1;i>=0;--i){ //check that this begins with <span if(newTextElements[i]. indexOf("<span")>-1){ //get the span name - sits // between the 1st and 2nd quote mark //Make sure your spans are in the format //<span id="someName">NewContent</span> startNamePos=newTextElements[i]. indexOf(‘"‘)+1; endNamePos=newTextElements[i]. indexOf(‘"‘,startNamePos); name=newTextElements[i]. substring(startNamePos,endNamePos); //get the content - everything // after the first > mark startContentPos=newTextElements[i]. indexOf(‘>‘)+1; content=newTextElements[i]. substring(startContentPos); //Now update the existing Document // with this element, checking that // this element exists in the document if(document.getElementById(name)){ document.getElementById(name). innerHTML = content; } } }
function splitTextIntoSpan(textToSplit){ //Split the document returnElements=textToSplit. split("</span>") //Process each of the elements for(var i=returnElements.length-1;i>=0;--i){ //Remove everything before the 1st span spanPos = returnElements[i]. indexOf("<span"); //if we find a match, take out //everything before the span if(spanPos>0){ subString=returnElements[i]. substring(spanPos); returnElements[i]=subString; } } return returnElements; } New Flow of ControlBy adding the above JavaScript code to our application, the following steps now happen on the server and on the browser.
Designing AJAX into Your ApplicationThe JavaScript outlined above can cope with the way Struts is used in most applications, including those that are much more complex than our simple example. However, you may find that following the points below makes it easier to write and use your code:
An updated version of this project, with AJAX enabled, can be downloaded here: struts-Ajax.zip ConclusionAJAX techniques promise to completely revolutionize how we build and use web applications. This article showed a simple technique to add AJAX behavior to existing Struts applications. It allows us to reuse our existing investment, not only in code but also in developer skills. As a nice by-product, it also allows us to write cleaner, more reusable, Java Struts applications. Resources
Paul Browne has been consulting in enterprise Java with FirstPartners.net for almost seven years. |
|