Professional Documents
Culture Documents
Introduction
Ajax or Asynchronous JavaScript and XML was introduced by Jesse James Garrett in 2005. He is
called the “Father of Ajax” .Ajax is a collection of concepts and technologies that allows richer and
more interactive user interaction with the web applications. The Ajax engine allows the user’s
interaction with the application to happen asynchronously — independent of communication with
the server. So the user is never staring at a blank browser window and an hourglass icon, waiting
around for the server to do something.
The most popular and the biggest user of AJAX is Google. Orkut, Gmail, the latest beta version of
Google Groups, Google Suggest, and Google Maps — are Ajax applications Google mail, Google
calendar and Google home page are some examples. In your Google mailbox the “loading” that is
displayed in the top right corner is using these Ajax technologies. The new Yahoo homepage too
uses some of these technologies. Another cool Ajax implemented website would be
www.pageflakes.com Others are following suit: many of the features that people love in Flickr
depend on Ajax, and Amazon’s A9.com search engine applies similar techniques.
In traditional webpages, the pages will be reloaded for each and every request. But in most of the
cases only a part of the page will be processed. Hence such a page reload is unnecessary. Thus
the usage of ajax plays a efficient role. In the webpages, that are using ajax, only the
part of the page that has to be processed will be transferred to the web server and the
processed data will be loaded in the page without a page reload.
AJAX internals
AJAX is not a single technology as mentioned earlier. It is important to remember that AJAX is not
Java or .NET dependent.
Whatever be your back end code, you can use AJAX to communicate with it. People prefer AJAX
for the high speed with which it works. It does it with three basic ways
And JavaScript binding everything together. So, how does AJAX does this sending request and
getting response from the backend server??
Using the XML Http Request object.
As we have seen enough of the theory behind the working of Ajax in struts let us see an example.
Simple example is loading a drop down depending on the selected item in another drop down.
We need to populate the characters in a “showcharacters” dropdown when a particular TV Show is
selected in the “showTVShow” drop down using AJAX. Let us see the Ajax request response cycle
for this scenario.
Let us take three TV shows which I like.”Lisse Maguire”,” That’s so Raven” and “Dhoom Machallo
Dhoom”. We need to populate the characters dropdown as and when the TV Show dropdown value
changes , so we decide to call the javascript in the “onchange()” of the select box.
<html:form action="showCharacters.do">
TV Show:
<html:select property="TVShowSelect"
onchange="retrieveURL('
showCharacters.do?tvShow=' + this.value);">
<html:option value="Lissie Maguire"> Lissie Maguire
</html:option>
<html:option value="That’s so Raven"> That’s so Raven
</html:option>
<html:option value="Dhoom machale"> Dhoom machale
</html:option>
</html:select>
<br>
Characters: <span id="characters"></span>
</html:form>
“’ showCharacters.do?tvShow=' + this.value”
We are appending the selected item with the URL as a query string. We can also just send the Url
and append the form contents in the java script.
function retrieveURL(url)
{
if (window.XMLHttpRequest)
{
// Non-IE browsers
req = new XMLHttpRequest();
req.onreadystatechange = processStateChange;
try {
req.open("GET", url, true);
} catch (e) {
alert(e);
}
req.send(null);
} else if (window.ActiveXObject) { // IE
The action class has to get the value selected in the TVShow dropdown and Get the appropriate
list of characters using the function getCharacters(String tvShow) .
if (tvShow.equalsIgnoreCase("Lissie Mcguire")) {
al.add("Lizzie Mcguire");
al.add("Mathew Mcguire");
al.add("Miranda");
al.add("Gordon");
}
} // End getCharacters()
} // End class
Then it sets the Appropriate characters in the session and returns the keyword “success” Thus the
control passes to showCharacters.jsp
Step 5: Write the contents you need to reload in the characters drop down
(“ShowCharacters.jsp”)
In the showCharacters.jsp we load the contents of the characters drop down by taking their
values from the session.
Remember to add the tag libraries and surround the code with a form tag.
ShowCharacters.jsp
<html:select property="TVShowSelect">
<logic:present name="characters">
<%ArrayList ch = (ArrayList)
request.getSession().getAttribute("characters");
String[] s = new String[ch.size()];
ch.toArray(s);
for(int i=0;i<s.length;i++)
{%>
<html:option value ="" ></html:option>
<%} %>
</logic:present>
</html:select>
Thus the showCharacters.jsp is the response from the Back end server. Once the response form
the server is got by the browser. It calls the processStateChange() method
So far, we have looked at the JavaScript to do the AJAX call (listed above) and the Struts Action,
ActionForm, and JSP (mostly the same, with the addition of tags). To complete our understanding
of the Struts-AJAX project, we need to look at the following JavaScript function that is responsible
for updating the current web page when the results from the server are received.
processStateChange(): The method name that we set before making the AJAX call. The
XMLHttpRequest/Microsoft.XMLHTTP object calls this method once the server has completed
sending back its response.
function processStateChange() {
if (req.readyState == 4) { // Complete
if (req.status == 200) { // OK response
document.getElementById("characters").innerHTML = req.responseText;
} else {
alert("Problem: " + req.statusText);
}
}
}
Here readystate is checked .If it is equal to 4 , it means the response is completely received and
the status of the response is checked to 200.
If everything fit in, the response is set as the innerHTML of the span “characters”. We can also
give the response to a div.
Thus we have done a asynchronous call to the back end and got the response and set it to a span
element. Only the contents of the span have been reloaded while the rest of the page remained
there.
Flow of Control
By adding the above JavaScript code to our application, the following steps now happen on the
server and on the browser.
One of the useful enhancements in Struts 2.0 is the introduction of AJAX Theme
The Ajax theme extends the xhtml theme with AJAX features. The theme uses the popular DOJO
AJAX/JavaScript toolkit. The new AJAX features include:
The framework provides a set of tags to help you ajaxify your applications, on Dojo.
To use the Ajax tags you need to set the "theme" attribute to "Ajax".Use the head tag to
configure the page for the Ajax theme.
URL
The "href" attribute must contain a url built with the URL tag
Example:
Initial Content
Set the "debug" attribute of the head tag to "true" to display debug information on the bottom of
the page
Indicators
Use indicators to notify the user that a request is in progress. The indicator should be hidden
when the page is loaded.
This indicator is an image:
Dynamic Div
The div tag is a content area that can load its content asynchronously. The div tag can be forced
to reload its content using topics. To define the topics that will trigger the refresh of the panel,
use the "listenTopics" attribute. This tag will load its content when the page is loaded, unless
"autoStart" is set to "false".
While Dojo supports crossdomain XHR using IFrames, the S2 Ajax tags do not (yet)
This div will refresh every time the topics "/refresh0" or "/refresh1" are published:
The simplest way to use the div tag is to provide an href attribute. For example
What this does after the HTML page is completely loaded; the specified URL will be retrieved
asynchronously in the browser. The entire contents returned by that URL will be injected in to the
div and will update every minute after a two second delay:
Include the attribute errorText in case the URL is not loaded
Submit
The submit tag can be used to update the content of its "targets" attribute with text returned
from the asynchronous request. "targets" is a comma-delimited list of element ids. The "targets"
attribute is optional.
Div 1
For using Submit button using an image add the attribute src
src="${pageContext.request.contextPath}/images/struts-rocks.gif"
If the submit button is used inside a form (href is not required on this case), the form will be
submitted asynchronously using
A submit button can be used to submit a form, even if it is outside the form, using "formId",
"formFilter" and "href". Note that in this case "href" is required.
Anchor
The anchor tag, like the submit tag; can be used to update the content of its "targets" attribute
with text returned from the asynchronous request. "Targets" is a comma-delimited list of element
ids. The "targets" attribute is optional.
This anchor will update the content of div1 and div2 with text returned form "/AjaxTest.action"
Div 1
Div 2
Update divs
If the anchor tag is used inside a form (href is not required on this case), the form will be
submitted asynchronously:
Submit form
Submit form
AJAX Client Side Validation
• Ajax Validation requires DWR servlet being setup, Dojo and the Ajax theme being used.
• In the Ajax theme, DWR is used for normal validation while Dojo handles everything else
(widgets, XHR, browser JS events etc.)
• In order for validation to function properly it is advised to use standard Struts Tags
Setup DWR
DWR could be setup by having the following dwr configuration (dwr.xml) at /WEB-INF/ directory.
If it needs to be in other places.