Вы находитесь на странице: 1из 24

Sprinkle Some AJAX Magic in Your Struts Web

Application

by Paul Browne

10/27/2005

AJAX is the latest revolution in web development circles, allowing rich dynamic interfaces deployed within a
normal web browser. Struts has been one of the de facto standards for Java-Web development for a number of
years, with a large number of applications already deployed. This article will show you how to combine the richness of
an AJAX user interface with your existing Struts applications.

This article shows a simple and elegant way to do this by including a couple of lines of JavaScript on your
JavaServer Pages (JSPs). While we show how to reuse existing Struts actions, the techniques are equally applicable
to the Java-Web framework of your choice. The method proposed will also allow a move to the next version of Struts
(Shale) or JavaServer Faces (JSF) in the future.

What is AJAX?
AJAX stands for "Asynchronous JavaScript and XML." It is a technique, rather than a framework (such as
Struts). The reason for the buzz around it is that it allows web pages to behave less like flat documents and more like
dynamic GUI apps that users might expect from their desktop environments. AJAX techniques can be used for all
recent browsers (including Internet Explorer and Netscape/Mozilla). It is already used by (among others) Microsoft
(for its Outlook web client) and Google (for Google Maps and Gmail).

Life Before AJAX


Most current Struts applications follow the standard "web page as a flat document" structure. If you wanted to
mimic the behavior of GUI desktop apps (such as those built using Java Swing, Visual Basic, or Delphi) you had two
choices: you could either send all of the information that might possibly required as part the web page with (a lot of)
JavaScript to handle the dynamic behavior (a slow and not very enterprise-Java way to do things), or you could do
constant form submits back to the server (an effective, if somewhat clunky, method). AJAX gives you the best of both
worlds: dynamic web pages, but with most of the application running in Java on your web server.

AJAX 101
AJAX is similar to existing Dynamic HTML techniques, with the addition of a "background" call to the server to get
new/updated information as required. The mechanics of AJAX have already been covered in detail elsewhere--take a
look at the Resources section at the end of this article for some good examples. The minimum you need to know is:

1. The XMLHttpRequest (or Microsoft.XMLHTTP ActiveX object if you are using Internet Explorer). These
objects can be called from the JavaScript on your web page. They allow you to request content from your
web server as a background call (i.e., the screen does not "go blank" as usually happens during a form
submit).
2. The content that the XMLHttpRequest and Microsoft.XMLHTTP objects return can be treated as either
XML or plain text. JavaScript (on your web page) can then update the page with this new content as
required.
3. The whole process can be triggered by the usual JavaScript events: onclick, onchange, onblur, etc.

Using AJAX in Your Struts Application


The chances are that if you are reading this article, then you are interested in AJAX's ability to create dynamic web
interfaces and would like to know how to add it to a Struts application. What are your options if you want to do this?

• Wait until the next version of Struts (Shale) incorporates AJAX techniques. For Struts developers starting a
new application this is probably the best option. The downside is that this will probably require moving to
JavaServer Faces--not a bad thing in itself, but this may entail fundamental changes if you have an existing
application.
• You could move to a new approach, like Direct Web Remoting (DWR) or Ruby on Rails, which are
specifically built for AJAX applications. While these are both very impressive frameworks, and are worth
taking a look at if you wish to consider web development without Struts, this option would mean rewriting
your entire application.
• Add AJAX to your existing Struts application. Since AJAX is a technique, not a framework, it is
straightforward to add it to Struts. For existing applications where stability (e.g., keeping existing libraries) is
important, this option is recommended and is the one we explore in more detail.

Some other advantages of our preferred option are:

1. It should not require any new libraries or server side code; only the Struts libraries and actions already in the
application need be used.
2. All of the parts of the solution--JavaScript, XML, Java and Struts--are already widely understood.
3. The application can be migrated to AJAX piece by piece; we can identify those parts which will most benefit
users, and then choose to upgrade them to dynamic AJAX behavior first.

Implementing the Solution


How do we actually implement our chosen solution? We start by reminding ourselves how a "standard" (non-
AJAX) Struts application works. In this application, the normal flow of events is as follows:

1. The user requests a screen by clicking a hyperlink or form submit button.


2. The web server runs the requested Struts Action, generating the web page.
3. The browser displays the page.
4. When the user presses Save, the information is posted to the server, where it's converted by the Struts
framework to an ActionForm class containing the posted data.
5. The Struts framework then calls the Struts Action that then processes the request (e.g., saves the data to
a database).
6. The page is rendered as per item 2, and the process starts again.

Existing Struts Application


A simple Struts application demonstrating this flow of events can be downloaded here: struts-non-ajax.zip. This
application, based on the sample applications provided with Struts, either hides or displays blue and green tables
depending on the values entered by the user. Figure 1 shows the screen on initial page load. Figure 2 shows the
screen after the user has entered values and pressed Submit. Although simple, it is enough to demonstrate a Struts
application at work.

Figure 1. Non-AJAX sample: Initial screen


Figure 2. Non-AJAX sample: Values entered, Submit pressed

The server-side code is as you would expect: a Struts Action that forwards to the (same) JSP using the
values defined in struts-config.xml. Some other points to note in this code sample are:

• The struts-config.xml file is set up to redirect all requests to http://localhost:8080/struts-non-


ajax/ (or the equivalent in your web server) to index.jsp.
• index.jsp contains a Struts form with two text boxes (showBlue and showGreen). The page also contains
<logic:equal> tags, but as the values for these text boxes are initially blank, the content within them is
not displayed.
• The user enters values (true or false) and presses the Submit button, passing control (via the Struts
Framework, reading struts-config.xml) to the SampleAction class.
• SampleAction logs the values, and then forwards back to index.jsp. A more sophisticated Struts
application would do more, such as saving to or retrieving from a database.
• index.jsp now evaluates the request; if showBlue or showGreen are true, the tables will be displayed.

There is nothing "wrong" with this application. After all, similar Struts projects have been deployed for years. But
how do we to add dynamic behavior to this application, without adding complex JavaScript or continual form submits?

*********************************************************************************************************************************** 2

Our First Struts AJAX Application


Take a look at the Figures 3 and 4 below. At first glance, they seem similar to our previous ones. The difference
is that after then screen loads (Figure 3) and the values in the textboxes are changed, the screen automatically
updates without the screen going blank, giving the result as per Figure 4. The normal Submit button is also still there,
should you choose to use it.
Figure 3. AJAX sample after page load

Figure 4. AJAX sample after AJAX call

Adding this AJAX behavior is surprisingly easy. The server-side code is the same as usual: a Struts
ActionForm to hold the data, and a Struts Action that performs the tasks required (e.g., database access) and
then forwards to the appropriate JSP to display the result.
Don't Just Sit There
If you wish to stop reading here (and skip the explanation of how this works) then here is all you need to do to
convert your Struts application to a Struts-AJAX application in a similar manner:

1. Include the Ajax.js JavaScript file on your web page (this file is part of the struts-ajax.zip sample file). Ajax.js
contains all of the JavaScript functions necessary to send and receive AJAX calls.
2. Ensure the parts of the web page that you wish to update during AJAX calls are surrounded by <span>
tags, giving each an id.
3. When something happens that should update the page (e.g., the onchange() method of a textbox), call the
retrieveURL() function, passing in the URL to the Struts Action that will do the necessary server-side
processing.
4. For page display/update, the easiest option is for the Struts Action to forward back to the same JSP. In our
sample, we trigger the AJAX call in the onchange() method of the showGreen/showBlue textboxes.

The JavaScript function retrieveURL() calls Struts on the server (via the URL provided), takes the JSP
response, and updates the web page being displayed, where the <span> tags on the existing web page match those
on the newly returned JSP. Simple!

The AJAX Solution in More Detail


When we converted the previous sample into an AJAX-Struts application we made three changes:

1. Added a JavaScript function to do the "behind the scenes" AJAX call to the server.
2. Added JavaScript code to receive the server response and update the web page.
3. Added <span> tags to the JSP page, which mark sections that will be updated during AJAX calls.

We will look at each of these in more detail.

Making the AJAX Call to the Server


There are two functions (listed below) that are used to call the server.
• The retrieveURL() function takes a parameter of the URL of the server and the name of the Struts form.
The URL will be called using AJAX and the values of the form passed to the server.
• getFormAsString() is a function that converts the values on the form named in retrieveURL() into a
query string suitable for posting to Struts on the server.

To use, simply add the retrieveURL() function to the onclick()/onChange() method of the event you wish to
trigger the screen update.

There are some interesting items going on in both methods.

Within the retrieveURL() method, the line req.onreadystatechange = processStateChange (note: no


brackets) tells the browser to call the processStateChange() method (which we talk through later in this article)
once the server sends back its response. This method (now standard in AJAX) also determines whether it should use
the Internet Explorer (ActiveX) or Netscape/Mozilla (XmlHttpRequest) object to ensure cross-browser compatibility.

The getFormAsString() method converts the HTML form into a string to be appended to the URL (which allows
us to do a HTTP GET request). This string is escaped (spaces are converted to %20, etc.) and is in a format that
Struts can use to populate an ActionForm (without Struts being aware of the special AJAX nature of the request).
Note that while we use a HTTP GET in this sample, it would be equally possible to use a HTTP POST by looping in a
similar manner and adding the form fields to the request.

function retrieveURL(url,nameOfFormToPost) {

//convert the url to a string


url=url+getFormAsString(nameOfFormToPost);

//Do the AJAX call


if (window.XMLHttpRequest) {

// Non-IE browsers
req = new XMLHttpRequest();
req.onreadystatechange = processStateChange;
try {
req.open("GET", url, true);
} catch (e) {
alert("Server Communication Problem\n"+e);
}
req.send(null);
} else if (window.ActiveXObject) {
// IE

req = new ActiveXObject("Microsoft.XMLHTTP");


if (req) {
req.onreadystatechange=processStateChange;
req.open("GET", url, true);
req.send();
}
}
}

getFormAsString() is a "private" method used by the retrieveURL() method.

function getFormAsString(formName){

//Setup the return String


returnString ="";

//Get the form values


formElements=document.forms[formName].elements;

//loop through the array, building up the url


//in the format '/strutsaction.do&name=value'

for(var i=formElements.length-1;i>=0; --i ){


//we escape (encode) each value
returnString+="&"
+escape(formElements[i].name)+"="
+escape(formElements[i].value);
}

//return the values


return returnString;
}

Updating the Web Page with the AJAX Response


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 <span> tags). To complete our understanding of the
Struts-AJAX project, we need to look at the three JavaScript functions that are 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. This method is
called by the XMLHttpRequest/Microsoft.XMLHTTP object once the server has completed sending back
its response.
• splitTextIntoSpan(): Loops through the response, picking out an array of <span
id="someName">NewContent</span> elements.
• replaceExistingWithNewHtml(): Loops through this array of span elements, searching for <span>
elements in the existing page with 'someName' and replacing them with the new content from the server.
Note that we get the returned content via req.responseText for robustness (since it allows us to
manipulate any text response), rather than req.responseXml (which is more powerful, but requires that
you return valid XHTML or XML).
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);
}
}
}

replaceExistingWithNewHtml() is a "private" method used by the processStateChange() method.

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;
}
}
}

splitTextIntoSpan() is a "private" method used by the processStateChange() method.

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 Control
By adding the above JavaScript code to our application, the following steps now happen on the server and on
the browser.

1. The page loads as per a normal Struts application.


2. The user changes a textbox value, triggering an onChange() event, which calls the retrieveURL()
JavaScript function.
3. This JavaScript function makes a (background) call to the Struts Action on the server, passing in all of the
form variables in a way that Struts will understand.
4. This JavaScript function also sets the name of a second JavaScript function, which will be called when the
server response is finished. In this case, it is set to the processStateChange() method.
5. As expected, when the server response is finished, the processStateChange() method is called.
6. The JavaScript loops through all of the <span>elements in the (new) server response. Where it finds a
<span> in the existing page with the same name, it updates it with the new content.

Designing AJAX into Your Application


The 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:

• To avoid duplicated code, it can often be better to use the same Struts Action and JSP for the initial
request (i.e., show full page) and the AJAX (update part of page) requests.
• Within the common Action (controller) class, decide which sections of the JSP page (all of the JSP or only
part of it) need to be sent to the browser. By setting flags in either the web server session or ActionForm,
the JSP page knows which sections need to be rendered.
• Within the JSP, use Struts <logic:equal> or JSTL tags to decide if we need to render a section of HTML
or not.

An updated version of this project, with AJAX enabled, can be downloaded here: struts-Ajax.zip

Conclusion
AJAX 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
• Sample code for this article
• Definition of AJAX
• "Using AJAX to Catch JavaScript Errors" (XML.com article)
• "Developing AJAX Applications the Easy Way" (java.net article)
• "An Introduction to AJAX" (dev2dev article)
• "AJAX on Rails" (ONLamp.com article)
• DWR: Direct Web Remoting Project
• Struts Framework Project
• JSF: Java Server Faces Project
Paul Browne has been consulting in enterprise Java with FirstPartners.net for almost seven years.

View all java.net Articles.

Are you adding AJAX to your web app?

Showing messages 1 through 74 of 74.

• Problem with server response Internal Server Error


2007-09-27 07:24:04 everett_zhou [Reply | View]

Hi Paul,

Your article just perfectly fits into my requirements, i.e. originally using Struts and some piece working but ugly.
Here is the scenario:

I have two radio buttons, one is for uploading a file and another for creating a file. Originally, I have to list all items
needed to create a file, even though I may just load a file. So with Ajax, I do not have to list all those items, rather I
want them to be listed only I click the button for creating the file. Here is related code:

In loadDesignFile.jsp:

…….

<html:radio name="loadDesignFileForm" property="createSfotMethod" value="Method3"> Upload SOFT file from


local Machine
</html:radio>

<html:file property="uploadSoftFile"> </html:file>

<html:radio name="loadDesignFileForm" property="createSfotMethod" value="Method4"


onclick="retrieveURL('/nimblegen/loadDesignFile.do?ask=COMMAND_NAME_1','loadDesignFileForm');"> Create
SOFT file now
</html:radio>

<logic:equal parameter="createSfotMethod" value="Method4">


<span id="theTable1">

PLATFORM <font color="red" size ="4"> *</font>


<html:text property="platform" size ="30"> </html:text>

platform_title <font color="red" size ="4"> *</font>


<html:text property="platform_title" size ="30"> </html:text>

…….

</span>
</logic:equal>

Ajax.js is just your file. I did not make any changes for LoadDesignFileForm.java and LoadDesignFile Action.java,
either.

After I click the button for creating a file, a window pops up and says: Problem with server response Internal
Server Error. This error is generated from function processStateChange(). I tried both firfox and IE and got the
same error. BTW, what are “ask=COMMAND_NAME_1” and id="theTable1"? It looks like they are not used.

Thank you very much.


• Great Intro, New revision
2007-08-12 16:00:09 shakerlxxv [Reply | View]

Paul, Thanks for the great intro to AJAX. It was just what I need to take the plunge. That being said, almost as
soon as I started using this technique, I encountered a limitation with the getFormAsString() function provided. I
found what seems to be a good way to revise your Ajax.js script by using the now standard prototype.js library.
This greatly simplifies the retrieveURL() function and eliminates the processStateChange() and
getFormAsString() functions.

The revised code looks like:

function retrieveURL(url,nameOfFormToPost) {
if((typeof Prototype=='undefined') || (typeof Element == 'undefined'))
throw("Prototype JavaScript framework Required");
if ( nameOfFormToPost && nameOfFormToPost.length )
{
var form = document.forms[nameOfFormToPost];
var formData = form.serialize(true);
}
new Ajax.Request(url,
{ parameters: formData,
onSuccess: loadResponse,
onFailure: ajaxError});
}

function loadResponse(req) {
// check return OK, should already be handled though
if ( req.status == 200 ) {
//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 ajaxError(req) {
alert("Problem with ajax response:\n " + req.statusText);
}

o Great Intro, New revision


2007-08-13 09:04:06 shakerlxxv [Reply | View]

Woops !!! That should read:


o

o var formData = Form.serialize(form);

• local javascript functions behave abnormal with this ajax technique


2007-04-07 15:13:47 robinbajaj [Reply | View]

I have a struts web project with a web page implementing CRUD functionality and also allows record navigation
with a set of First, Last, Previous, Next buttons.
another set of buttons is New, Save, Reset,Cancel.

First, Last, Previous, Next and New buttons comprise the _navMode buttonset and Save,Reset,Cancel buttons
comprise the _saveMode buttonset.

Initially on page load, I was enabling the _navMode buttonset and when the user clicks on New Button, the
_saveMode button set gets enabled.

After I used this article's technique to incorporate AJAX on this webpage, it started allowed navigating the records
(first, last, etc.) without having to refresh the whole page. But I got a problem in lieu of this functionality. That
problem is that the local javascript functions don't get executed properly and hence the buttonmode functionality
starts working very erratically.
For example, when the pageload happens, the _navMode buttonset is enabled (as earlier).
but when I start navigating by clicking the previous or next buttons, all the buttons on the page (both _navMode
and _saveMode buttonset gets enabled).
this problem didnt happen earlier.
I have even tried calling the setButtonMode() javascript function right after calling the retrieveURL() function
provided by the author, but I have noticed that that function does not get executed at all.

Any pointers as to what could be causing this issue?


• IE problem
2006-09-21 09:55:29 dchacons [Reply | View]

Hi Paul!!

Paul I used ajax on my struts application like your explain in your article, all works fine on firefox and netscape, but
when I run my application on IE 6 doesn´t work at all, no input between spans is updated, what it should be? I
really need help with this! Someone pass for the same case?

Thanks for your help


o IE problem
2006-09-21 17:51:50 dchacons [Reply | View]

The Solution:

It was a cache problem of the IE, it solved when put this on my JSP:

<%
response.setHeader("Cache-Control","no-cache"); //HTTP 1.1
response.setHeader("Pragma","no-cache"); //HTTP 1.0
response.setDateHeader ("Expires", 0); //prevents caching at the proxy server
%>

Hope this help


 IE problem
2006-09-22 06:10:47 dchacons [Reply | View]

Another solution, that you can use if the first doesn´t work:

Make a llavascript that generate aun unique url each time retrieveURL is call, so the IE don´t never have the
url in cache:

function uncache(url,form){

var d = new Date();


var time = d.getTime();

if(url.indexOf("?")<0){
url += '?time='+time;
}else{
url += '&time='+time;
}

<string>retrieveURL(url,form);
}
 IE problem
2006-09-22 06:11:44 dchacons [Reply | View]

Sorry, witout the "<string>":

function uncache(url,form){

var d = new Date();


var time = d.getTime();

if(url.indexOf("?")<0){
url += '?time='+time;
}else{
url += '&time='+time;
}

retrieveURL(url,form);
}
• progress bar on browser
2006-09-04 22:10:43 rrahulgupta [Reply | View]
Hi Paul,
I have deployed strust-ajax example, when I am changing value of 'Show Green' or 'Show Blue' text-boxeson,
browser showing its progress-bar running. So, it is looking like page has been submitted.
My confusion is, if you are using XMLHTTPRequest, then why it is looking like page-submission?

Thanks in advance.
-Rahul
• Ajax with tag problem
2006-08-03 05:36:38 eleni [Reply | View]

Hi, I have a problem with Ajax. I have a submit form where I have declared a <html:select> tag and some
<html:option> tags. When submit button is clicked I call myretrieveUrl() javascript function. In case I have
selected more than one option values, the only value that is passed is the first one. The corresponding property
attribute is been saved into the Bean as an Array and not as a String. I have set the multiple atribute too.
The code has no problem without Ajax (passes all the selected values).
• Can I command action?
2006-06-14 01:28:40 mieder [Reply | View]

Hi Paul!

I use Ajax in my struts application to execute a specific action:

In javascript I call Ajax:

retrieveURL("roomBookingAction.do?ask=COMMAND1","roomBookingBean");

in my struts-config.xml file I have:

<action input="/booking.jsp"
name="roomBookingBean"
path="/roomBookingAction"
type="eresonline.RoomBookingAction"
validate="true">
<forward name="forward" path="/bookingRequest.jsp" />
</action>

The action is executed with the given bean and works well, but I need it to do the forward part aswell, how do I
accomplish that? Is it possible?

Thank you!
o Can I command action?
2006-06-14 02:04:21 paulbrowne [Reply | View]

This is a similar problem to the question below (search for 'Error Handling - Answer to Email Query').

The difference here is that we want to forward based on a 'normal' , non-error event.

Answer is similar: You will need client side javascript to identify and carry out the forward.

This additional complexity is one of the reasons why you're better (if you can) using an Ajax framework such as
DWR , Dojo or Google Web toolkit. This Blog Post lists some of the more common frameworks.

Paul , Technology in Plain English


• An amendment on Command an Action
2006-06-13 07:53:52 mieder [Reply | View]

I have seen the retreiveURL request in Ajax does not work without ask=COMMAND inline? What does this
mean..?
o An amendment on Command an Action
2006-06-13 08:14:11 paulbrowne [Reply | View]

It is a piece of code that should have been removed for the final version of this article.

The code was to allow us to implement a command pattern within Struts and has no direct relation to Ajax.
Paul , Technology in plain English
• Command an Action
2006-06-13 07:50:20 mieder [Reply | View]

Hi Paul!

I use Ajax in my struts application to execute a specific action:

In javascript I call Ajax:

retrieveURL("roomBookingAction.do?ask=COMMAND1","roomBookingBean");

in my struts-config.xml file I have:

<action input="/booking.jsp"
name="roomBookingBean"
path="/roomBookingAction"
type="eresonline.RoomBookingAction"
validate="true">
<forward name="forward" path="/bookingRequest.jsp" />
</action>

The action is executed with the given bean and works well, but I need it to do the forward part aswell. I've seen that the
url request does not work with the ask=COMMAND1. What does this mean, can I use it in my action?
Thank you!
• Javascript Unspecified error
2006-06-06 03:53:53 harisharma [Reply | View]

Hi, I'm getting an 'Unspecified error' when I try to use Ajax.js in my struts application. I traced the error to the line
req.open("GET", url, true);
I am using IE 6, any help would be appreciated

o Javascript Unspecified error


2006-10-13 07:05:42 artgeigel [Reply | View]

I'm having the same issue. You wouldn't happen to be executing on a server using SSL? I have a valid SSL
cert and think it's affecting my AJAX performance.
 Javascript Unspecified error
2006-10-13 07:23:04 artgeigel [Reply | View]

Grrr... my problem was that I had [ajax_object].onreadystatechange before [ajax_object].open

Put this after the open statement and it might work out for you too.

Funny how it worked in FF but not IE...


o Javascript Unspecified error
2006-06-06 04:00:23 paulbrowne [Reply | View]

Have you tried any or all of the following to debug the code and see the request that is being attempted to be
sent?

1) Use Message.alert throughout the code


2) User Microsoft Script Debugging
3) Use Mozilla Venkman to debug.

Watch out for the request being too large or improperly formed.

Paul
• Problem with charset
2006-05-19 13:55:41 moonlight [Reply | View]

Hello everyone,

I've put this solution on one of my webapps and it works fine, except for the charset.
Because I receive entry in my original language (Portuguese) I use some characters like í, ã, ô and etc. I need to
use accentuation and it is somehow being lost there.
When I make the struts call directly, they work fine. When I use this javascript, it just doesn't work, replacing this
characters with a "?" symbol.
I would like to know if someone has had this problem and would know the solution.
The charset I use is ISO-8859-1

Thanks very much


o Problem with charset
2006-05-20 05:11:44 paulbrowne [Reply | View]

This is probably not going to help you much , but the problem sounds like it is in the Javascript manipulation of
the text *after* the ajax calls returns.

As the article says, if you have a choice (i.e. you can choose a standard Web library), go for one of the
emerging Java-Ajax standards (list here). This list has not yet been updated with the news that Google has
released it's Java Ajax code.
• Why not just use tried and tested GUI API frameworks?
2006-03-12 04:03:30 joepop [Reply | View]

All the Ajax methods and libraries SU*K! Xerox PARK invented GUI 25 years ago. Many others including Apple
and Microsoft has been perfecting the technologies ever since and created excellent reusable GUI Classes.

Why are you debating among many inferior methods when it is possible to build reusable Ajax GUI API to build
superior online applications at less cost?
http://www.cbsdf.com/misc_docs/why-gui-api.htm
http://www.cbsdf.com/misc_docs/gui-api-brief.htm

What else you need? What chance any other framework has and can offer? This is not a vapor where. The web
site described a simple process to build Ajax GUI Classes for any developer to create his own GUI Classes.

The web site says that it is possible to create GUI Class for any component, which is better than comparable
Java/Swing GUI Class. The web site and challenged the world to prove it wrong. If you are a technology super star
then try to find any flaw in the process.

It they are right, common sense eventually prevails and all the other Ajax frameworks and methods will be
marginalized.
o A good comparision of different Ajax frameworks is on this blog.
2006-03-20 12:54:40 paulbrowne [Reply | View]

After I wrote the above article, I blogged on the subject of 'If could could choose an Ajax-Java framework ,
which would it be?'

The blog post can be found here: http://www.firstpartners.net/blog/technology/2006/03/01/web-20-and-


enterprise-java-move-over-struts/

My main criteria for choosing a framework is a) will my investment in time learning it pay off in terms of clients
that request me to use it and b) will the client be able to find people who are experienced in that framework if I
am no longer available.

Note that the frameworks choosen in the post are not technically the best solution, but the most likely to be
widely adopted.
• Update Solution to this article - from the author
2006-03-01 02:42:07 paulbrowne [Reply | View]

To underline the purpose of this article: It is best used for 'legacy' applications where you cannot change the
architecture / libraries used, but you also need Ajax.

For all cases , you're probably better you use a framework. A blog post (from the Author) on the rapidly evolving
frameworks in the Enterprise Java space is here:
http://www.firstpartners.net/blog/technology/2006/03/01/web-20-and-enterprise-java-move-over-struts/
• HI Some Imp Assumptios
2006-02-27 22:09:01 sandeepparkhande [Reply | View]

HI Paul

What is Exact Meaning Of AJAX


Asynchrnous Java and XML
What is mwan by Asynchrnous?
Where we can you XML in That ?
Tell me your how your application stands for Database ?
Where we can use AJAX ? And where we won't ?
• about push
2006-02-09 20:17:48 qsdfedc [Reply | View]

Hi Paul,
After I consult your example, it want it do it show immediately each webpage of temperature, then increase I newly
pieces of realtime() at Ajax.js

function realtime(){
.
.
setTimeout("realtime()",1000)
retrieveURL('/struts-ajax/sampleajax.do?ask=COMMAND_NAME_1','inputForm');
}
AND
.jsp
<body onload="realtime()">

realtime() Show it is normal, but the temperature dealt with out from Action can not show on webpage normally,
Could you tell me it is there that has gone wrong probably.

PS.
I is it translate the article to come with the translation software, if there are syntax mistakes, please don't mind.
I have watched your discusion with eelan, the idea of eelan is a little similar, the thing which I want to make, but I
do not understand his method very much a bit.
o about push
2006-02-10 00:27:25 paulbrowne [Reply | View]

As per the previous item on this thread (below):

This code looks like it will do the ajax call once per second. I am not sure how ajax will perform under those
circumstances.

My suggestion is to modify the code so that the setTimeOut() is still 'firing' an event every second, but *before*
you make an ajax call, check that any previous ajax calls have returned.

The page (should) perform in the same way - if the server is slow, firing loads of Ajax calls is not going to make
any difference

Paul
http://www.firstpartners.net/blog/category/web/ajax/
 about push
2006-02-13 19:24:20 qsdfedc [Reply | View]

Hi Paulbrowne,
I have already found the problem that webpages can not be newer.
The reason is at the newer time, will read the file of Temporary in webpage, so need to revise its
establishment when use IE, but which uses Firefox will not have this question,
Thank you for your answer very much, hope when I am problematic next time, you can still help me.
• Solution Required for Problem in "Ajax in Struts-based Web Application"
2006-02-09 02:28:36 bibroy [Reply | View]
Solution Required for Problem in "Ajax in Struts-based Web Application"

//////////////////////////////////////////////////////////////////////////////////////////////////////////////

A highlevel view of the pseudo-code is follows:

AjaxFunctionOuter (){

....some code specific to AjaxFunctionOuter

for-loop(...){

AjaxFunctionInner ();
}
}
AjaxFunctionOuter works fine in all the cases both in terms of request-dispatch and response-processing
The problem is related to AjaxFunctionInner which is described in the following paragraphs:

Case I: [when the req.open(.., ..., true) for AjaxFunctionInner ]

AjaxFunctionInner does work in terms of request-dispatch to struts-action for all the iteration in the for-loop.
AjaxFunctionInner does NOT work in terms of response-processing except for the last iteration in the for-loop.

This case is same for IE and mozilla-based browsers(such as netscape, firefox, mozilla).

Case II: [when the req.open(.., ..., false) for AjaxFunctionInner ]


A) For IE:
AjaxFunctionInner does work in terms of request-dispatch to struts-action for all the iteration in the for-loop.
AjaxFunctionInner does work in terms of response-processing for all iterations in the for-loop.
B) For mozilla-based browsers:
AjaxFunctionInner does NOT work in terms of request-dispatch to struts-action for all the iteration in the for-loop.
AjaxFunctionInner does NOT work in terms of response-processing for all the iteration in the for-loop.[THIS IS
OBVIOUS]

Now what appears from the above 2 cases is that for multiple-sequential ajax requests (such as those that
might occur in a for loop) there appears to be some issue related to intercepting the response and subsequent
processing.

Case II (A) do not offer much hope since it defeats the very purpose of "A" of AJAX. Now I have been
through quite a handful of articles/FAQ related to AJAX, but to no avail. I have tried Javascript closures, but that
too do not seem to work.

Note: I am using POST (in call to open method) for all cases since I am doing form submission.

Let me know if anyone has a solution to offer in view the above perspective and also whether I am missing
something.

o Solution Required for Problem in "Ajax in Struts-based Web Application"


2006-02-09 03:29:55 paulbrowne [Reply | View]

This answer is not going to help you very much, but it could help other people reading this article who have not
started their project yet :-)

A big disadvantage of using custom code (be it javascript or Java) instead of a framework (such as Dojo or
DWR) is that most of the frameworks have already seen , and resolved, these kind of problems. Of course , if
you have no option but to use the custom solution in this article , this advice if of no use!

I have limited experience with 'multiple ajax calls' within a loop , mainly because it is very close to being a code
smell - how do you know which of the muliple calls is returning? Do you know if your browser supports multiple
calls? Canyou test all possible permutations of calls coming back early / late (unlikely).

I would suggest either

1) sending all required information as part of a single ajax call, and parse the response as required

or

2) Define some mechanism to 'queue' requests, and wait until the previous request is finished before sending
another.

Paul , http://www.firstpartners.net
 Solution Required for Problem in "Ajax in Struts-based Web Application"
2006-02-10 02:25:35 bibroy [Reply | View]

Hi Paul,

Infact, after I posted the problem I was mulling whether to give it a try by posting all information in a single ajax-
call or not and hence do away with the challenge posed by looped multiple ajax-calls....and I did it...and it
worked!

However now I am facing a different problem..It is something like this...


There is table to which multiple rows can be added ..the rows are filled by ajax calls...rows may be deleted as
well in which case the deletion is done from client-side javascript call and then refreshing the undeleted rows
using the same ajax call...

Now things work fine till the number of rows are limited to five(in mozilla-based browsers) and 3(in
IE).....However if the no. of rows exceeds the aforementioned, then ajax-call ("send" part) fails to dispatch the
request and the Javascript console displays the following error:

Error: [Exception... "Component returned failure code: 0x80040111 (NS_ERROR_NOT_AVAILABLE)


[nsIXMLHttpRequest.status]" nsresult: "0x80040111 (NS_ERROR_NOT_AVAILABLE)" location: "JS frame ::
http://localhost:8080/catissuecore/Distribution.do?
operation=add&pageOf=pageOfDistribution&menuSelected=16 :: processRequestOnSpecimenIdChange :: line
370" data: no]
Source File:
...............
Line: 370

Now line 370 is:


if (req.status == 200) {

Evidently the response is unavailable since the request itself failed....Any pointers ??

As for framework...I have not used any as of now...though I need to do subsequently to reap the benefits of the
same...But given the scenario as of now in mycase I feel that a framework is not pressing need.
• HTML:FILE creating problem while using ajax
2006-02-08 21:20:42 sulakshana_jathar [Reply | View]

I have tried using ajax in my application where database hit is done onchange of dropdown values to populate
other dropdowns. My form has html:file for attachment.since this is used i am getting error while implementing the
js and functionality using ajax
o HTML:FILE creating problem while using ajax
2006-02-09 03:06:36 paulbrowne [Reply | View]

Does it work without this field?


 HTML:FILE creating problem while using ajax
2006-02-13 01:55:09 sulakshana_jathar [Reply | View]

Yes it works perfectly fine without this feild.


 HTML:FILE creating problem while using ajax
2006-02-13 02:09:16 paulbrowne [Reply | View]

If you are using the code from this article, then the Ajax call is doing a GET request - this appends everthing to
the URL , similar to the URL you seen when you do a search in Google.

Problem is that this is limited in most browsers to about 4096 characters, and so doesn't work well with most
browsers.

The two choices are:


1) Use a *post* request in the ajax call (this is simple enough, but you'll need to google for more information as it
is not covered in the article)

2) Sun Java Blueprints gives a good example of using Java Server Faces (JSF) with Ajax. This is a very different
approach from this article in that it does not use Struts, but it may be an idea that you can use.

Paul , http://www.firstpartners.net/blog/
 HTML:FILE creating problem while using ajax
2006-02-13 20:57:11 sulakshana_jathar [Reply | View]

Thnx Paul for your reply. I have used "POST" method instead of Get. I will have a look at the other option that
you have suggested. Using Post my application is working perefctly fine but as soon as i use html:file tag inmy
jsp then it creates a problem.
• HTML:FILE craeting problem while using ajax
2006-02-08 21:20:17 sulakshana_jathar [Reply | View]

I have tried using ajax in my application where database hit is done onchange of dropdown values to populate
other dropdowns. My form has html:file for attachment.since this is used i am getting error while implementing the
js and functionality using ajax. Can anyone help me in solving this?
• getFormAsString may not be good enough
2006-02-08 13:46:37 czhao [Reply | View]
Is there a way to "post" instead of "get"
o getFormAsString may not be good enough
2006-02-08 13:53:03 paulbrowne [Reply | View]

yes, a quick google for 'XmlHttpRequestObject documentation' will show the available methods.

I think one of the articles referred to in the links section also has the required info.
• retriveURL
2006-02-06 05:52:06 agustinmu [Reply | View]

Hi, I have a problem. May be I don't catch the main idea.


I have in my JSP a list ( <html:select> </html:select>) and in the "onchange" atributte y put de server call, but
when I click in some list option nothing happen. This is what I have in the JSP

onchange="retrieveURL('/strutajax/buscarProducto.do,'categoriaForm');"

The categoriForm is the input action form for de buscarProducto action.


What I'm doing wrong?
Thanks
o retriveURL
2006-02-06 06:27:40 paulbrowne [Reply | View]

1) Are you surrounding the sections to be changed with <span id="somename"> ... html select here ...
</span>?

2) Have you tried debugging as per the post below?

Paul
 problem with the server
2006-02-07 06:13:17 agustinmu [Reply | View]

Hi, I found my error. It was a stupid one. Shame on me. Now I have another problem. When I make the Ajax
call
retriveURL('/buscarProducto.do', categoriaForm).

It seems tha it don't found the action. Because alert me that it was a "Problem with the server respone". It
enters in the processStateChange() function. I'm doing it well?

Thanks
 problem with the server
2006-02-07 06:21:46 paulbrowne [Reply | View]

Try the following:


1) remove the .do from the end of the url you are using.

If this does not work , try opening the same url in a normal browser and resolve the issue as per a normal
web page.

Paul

http://www.firstpartners.net
• Powerful Ajax technology By combining my code
2006-02-02 22:23:52 sandeepparkhande [Reply | View]

Hi i am try to use ajax. in my project which is in Strut. But it was giving not tiles.template error can you mail me
why it was giving error like that ?

************New Discovery******************
One Imp thing

I am created servlet name Action1 and on the retriveURL function i call that servlet i wrote all my logic there
and i am outing some content like

out.println("<span id='tab1'> New Content </span> ">

the jsp is collecting response text as that and replaced the existing span tag in jsp
<span id="tab1> Old span Tag </span>

So the complete replacement of tag is there and new content are available there. we can get the variables in the
scope also i replaced all the html tags successfully on my project by using you java scope

Good thing is that the ActionForm class is not much complex in large application. We donot have to use logic tag
again and agian

But problem is that we can out only out html tag not the html tag lib tag beacause browser is not understand that
Its good solution as i implmented in my project with good reposnse But if we combine you application for html tag
lib and my application for the html tag then it is the best solution today available Please respond me
**************************************
o Powerful Ajax technology By combining my code
2006-02-03 00:24:57 paulbrowne [Reply | View]

I'm not sure if I fully understand the problem, but I can make some suggestions as to how to debug your code.

- Get a Javascript Debugger such as Mozilla Venkman or Microsoft Script Debugger.


- Add Window.Altert (crude but effective) throughout your javascript code so see what is going on.

The Three areas you need to concentrate on are:

1) *Before* the Ajax call is made to the server - is the call actually being made , and what values are being sent.

2) On the Server, what JSP page is being rendered and what HTML is being sent back to the client.

3) *After* the Ajax call is made, is the callback function being called. What values are passed to it? For the
Dynamic find and replace of the Span / Div tags , what values is it trying to find and are these being replaced
successfully.
Paul Browne http://www.firstpartners.net/blog
• Error Handling - Answer to Email Query
2006-01-11 07:08:30 paulbrowne [Reply | View]

QUESTION
I am in the middle of evaluating using AJAX for a particular feature in our Struts based application. The
scenario is as follows: There is a web page containing list of users. Along side each user name there is button for
enabling/disabling. This is an ideal place for using AJAX where I can just change the label of the button between
enable and disable. But what happens if a database error occurs in changing the state of user access?

We have got a error.jsp already in place. Till now we have been redirecting to it using findForward and set
the html:errors property in the action class.

ANSWER
The problem you mention is a common one: With Ajax, as you are not displaying a new web page each
time, how do you show errors? Here are 2 (of many possible) solutions.

Solution 1)
Display your errors in a section on the *same* page (e.g. like Struts Validation Errors do). To implement this,
follow the article (to allow for dynamic replace of sections of the web page). Keep a section of the page for errors.
When no errors, this will be blank. With errors, trap the exception / error and display an appropriate error in this
section.

OR

Solution 2)
In the *callback* Javascript function for Ajax, check for an error (to do this you will need to catch the error on the
serverside, then pass down some sort of error code via the ajax response). If there is an error code, use javascript
forward to an error page.

Paul Browne , FirstPartners.net


• Trouble in running the app
2005-12-08 10:36:43 kshivapad [Reply | View]

I didn't take the application as is: but copied some componenets of it. The problem is: In retrieveURL js function,
not getting any req object.
req = new ActiveXObject("Microsoft.XMLHTTP");
alert('req:'+req);

Am I missing something? I copied index.jsp, ajax.js, updated my struts-config with sampleaction and all.. also
copied antlr.jar, jakarta.oro.jar,

Thanks
o Trouble in running the app
2005-12-08 10:41:29 kshivapad [Reply | View]

I didn't finish it. I am sorry. The request is also going to server, sending the response back to server.
alert("Ajax response:"+req.responseText);

above statement does not have any text - no response. It's null.
 Trouble in running the app
2005-12-08 12:31:53 paulbrowne [Reply | View]

I'm not quite sure of your question:


1) What Browser (Type and Version) are you using?
2) On one hand you say you can't get the Req object, then the follow up says that the req object has no
response text!! - I'm a little confused.

Remember that Ajax calls are asynchronous - you tell it the method you want called when the server is finished,
then use that method to handle the server response.

Paul , Firstpartners.net
 Trouble in running the app
2005-12-08 11:38:52 kshivapad [Reply | View]

My mistake, sorry. Missed welcome action.


• COMMAND_NAME_!
2005-11-19 07:22:29 javajman [Reply | View]

What is the COMMAND for?

ask=COMMAND_NAME_1

Was looking for what it referenced and could not see it. I have an idea it's the value in the textbox,

but why COMMAND_NAME_1 ?

Is that a javascript thing?


o COMMAND_NAME_!
2005-11-21 11:44:50 paulbrowne [Reply | View]

Good Question: The simple answer is that I should have removed the 'Command_Name' from the Article / code
sample.

Longer answer is that an earlier draft of this article used 'Command Name' to map to a required action on the back
end - similar to a Gang of 4 Command Pattern / or the one that the guys from Struts have available on apache

Paul, Firstpartners.net
• In Response to a question by email...
2005-11-12 13:20:55 paulbrowne [Reply | View]

Question
I have been trying out your Ajx+Struts tutorial. Its very good. I could get it working in the second go itself. But,
there seems to be one small issue. I don’t understand what I did wrong. My problem is :-

1. I have a page A which when submitted passes on a date and goes to page B.

2. In the page b, I need to refresh the page every few seconds.

What I have done is as follows:-


1. Page A uses ActionA and FormA to take the date and pass it on to db get another date value from the db and
locad Page B with the new date in it.
2. Page B uses your ajax script to call Action B and Form C to get values from db for the date and show it on
screen. This call is put into a javascript so that it will be excuted every 5 seconds.

My problem is that after the first refresh. The retrieveURL() is called only once. From the second refresh it is not
getting invoked. I tried removing the javascript and placing the retrieveURL() on a link and clicking on the link. The
same problem exists there also. After the first load. It doesn’t seem to execute. I am attaching herewith the jsp,
action and form of page B. Can you pls check. I am really stuck. I have been fighting with this since yesterday and
I need to fix it up by tomorrow. Would really appreciate if you can find time to glance through the code.

Reply
Your question is a good example of how to take the code in the article and build it into a 'real world' situation. To
repeat that in other words - readers trying out only the article will not have the same problems.

A couple of useful things to know about ajax/ javascript in general (and might help in this situation) are:

o For the 'refresh the page every few seconds' the solution sounds like using the Window.settimeout() method
- you can set javascript to run in 5 seconds time etc. More details on the method can be found at Javascript Kit
o After an ajax call is received, you will need to set the call up again for another 5 seconds.
o I'm not clear on how the pages (a,b,c) relate to each other. The article uses one page and 'span' tags for
clarity/ ease of use. If you need something more complicated I would check that the data is get transmitted as
you expect (yes, this probably means adding 'alert()' functions to your code).
o Ajax is great , but it can be harder to debug (as so much happens behind the scenes. I suggest using either
the Mozilla Venkman or the IE Script debugger to check what is going on

Hope this helps


Paul
FirstPartners.net
o In Response to a question by email (part 2)...
2005-11-15 05:53:37 paulbrowne [Reply | View]

A couple of other pointers when extending the example:

 It's probably better to include the all the javascript you will need on the initial page load.
Even better , have the javascript in a separate .js file and call it as required.
 Due to 'text processing' nature of the replace old content with new, having javascript within
the 'span' tags can confuse things - another reason to use the best practice in the previous point.
 When the Ajax callback occurs, even though the page is updated there is no page
onload() or similar method fired. If you want to trigger an event you must explicitly call it from within the
Ajax callback method that you specified.

Hope this helps

Paul
• AJAX
2005-10-31 10:36:21 eelan [Reply | View]

I was wondering why you didn't mention another solution. Have the AJAX call return the table HTML. That way
you could avoid having most of that messy Javascript and reuse the same JSP logic that created the table in the
first place. It is not a suitable solution in all situations but it seems worth mention for this article.
o AJAX
2005-11-01 01:47:13 paulbrowne [Reply | View]

That solution is valid, but the way the article does it means you can use an asychronous call (more robust over
a network).
 AJAX
2005-11-01 09:09:00 eelan [Reply | View]

I guess I am missing what you are saying. I am saying still do the asynchronous call but what you get back
can either be just the plain data like in your article or you can get back the table HTML snippet that you can
simply plug into the DOM to replace the old table. For certain situations returning HTML may be the best
solution IMHO but all the AJAX articles I read never mention that approach.
 AJAX
2005-11-01 12:58:05 paulbrowne [Reply | View]

The main idea of searching and replacing the <SPAN> tags is to make the Javascript on the article
Generic. Returning HTML is not as sophisicated, but is a nice first step into Ajax from an existing Struts
application.

As far as I know , Google Maps and GMail use the return XML then manipulate in Javascript approach -
probably better if you have access to a full Ajax library (e.g. The XSLT javascript lib that Google have
open sourced).
 AJAX
2005-11-01 13:52:14 eelan [Reply | View]

For the problem in the article it seems simpler to replace all that Javascipt in your example with

if(http.readyState == 4){
var myTable = document.getElementById(tableId);
myTable.innerHTML = http.responseText;
}

Anyway, your article was good though I would have prefered a problem or some requirement that
required the use of XML and "sophisticated" techniques. If there is a clear reason to never return
HTML when using AJAX I'd be interested in learning.
• reinventing a wheel?
2005-10-31 04:30:27 shevit [Reply | View]

The idea is good, but not really new.

AjaxAnywhere does the same without JavaScript coding.

http://ajaxanywhere.sourceforge.net
o reinventing a wheel?
2005-11-01 01:51:39 paulbrowne [Reply | View]

Thanks for the link.

I'm a strong believer in using existing libraries where possible. I haven't (yet) used Ajax anywhere, but it could
be a good solution. From looking at the project though , I would rephrase and say ' without the developer need
to use javascript' , as the Javascript code is still there, but generated automatically.

Some projects may not be able to use this approach (a) because they do not want to introduce additional
libraries or (b) they want control over the Ajax code themselves.

Paul
www.firstpartners.net
• Write javascript manually?
2005-10-29 10:13:15 iusr [Reply | View]

Then I think the "prototype.js" library is better, for it's more flexible.
o Write javascript manually?
2005-10-29 12:02:24 paulbrowne [Reply | View]

Most of the friends that I got to review this article laughed about me using Javascript as they know how much I
hated the stuff (before you flame me , read on).

My previous objections were mainly to do with the lack of tool support , going back about 5-7 years ago, and
the lack of structure (again from a long time back).

The change of opinion to advocating Javascript has to do not only with Ajax (which makes it worthwhile to do
Javascript , given that you can use a small bit of it to pass control to the server , which as an Enterprise Java
Developer is always my preferred option), but also the improved tool support (think the Venkman debugger
from Mozilla) and also the standardisation of libraries (including the one you mention).

Using a library almost always is better than coding your own - so thanks for the recommendation and if
anybody else has suggestions , let me know!
 Write javascript manually?
2005-10-30 01:50:22 iusr [Reply | View]

One thing you metioned is quite right, "you can use a small bit of it to pass control to the server , which as
an Enterprise Java Developer is always my preferred option". Most Java EE developers do not have enough
time to master JavaScript.
Besides, in my current project I used a complicated script to generate a form according to some fields the
use inputs, but found IE would terminate unexpectedly -- even now I'm quite confident on my script for I'd
been testing it on Mozilla Firefox for quite a long time. And yesterday I gave up, passing that job from client
side JavaScript to a JSP at the server side and with AJAX I glued them together. Life wouldn't be better:)
 Write javascript manually?
2005-10-30 01:42:26 iusr [Reply | View]

Yeah, a scripting language like JavaScript is hard to write yet still harder to debug:S After 1 year practising it
everywhere in our projects(making my leader's head ached), I found myself loving it more and more each
day.
My opinion was, why use a "submit-check-report" paradigm when we can use AJAX or only JavaScript to
check the input fields in the background? What's more, with JavaScript we can easily change nearly every
attributes of an element, not only their styles, etc.
PS: I found the references at xulplanet.com very helpful, and XUL is great, too:)
 Write javascript manually?
2005-11-01 01:55:00 paulbrowne [Reply | View]

Don't get me wrong , I don't think writing Javascript is hard (I think most Enterprise Java developers could
master it easily), i's more that I think maintaining it is difficult. I'm half hoping there will be deluge of posts
explaining that I'm wrong and that here are the methods / tools on how to overcome this problem.

Yes moving to a dynamic, fluid interface validating single fields as they change would be much better.
Remember that Users are used to the change-submit-see new page from the last 10 years and we
should not shock them with too much too soon!

Paul
www.firstpartners.net
 Write javascript manually?
2005-11-01 04:05:45 iusr [Reply | View]

Then I should admire your ability~


I mixed up several methods for creating HTML elements, manipulating their attributes and styles,
appending and removing their child node(s), check the types and values of parameters in order to
avoid type casting errors and illegal values after my scripts were used by other developers, what's
more I must remember the types are weak and a variable might be assigned fautily at any time...
It's might be not hard, but really boring, if I want my script to be more robust.
 Write javascript manually?
2005-11-01 12:59:29 paulbrowne [Reply | View]

or maybe you're just more honest than your average J2EE developer!
• Very nice...small change required
2005-10-27 08:32:53 mikemaruffi [Reply | View]

This was very easy to get up and running...Very nice

I made a change to the getFormAsString function to only add checked radio button name/values to the query
string. Without this modification, all possible radio button values were included in the query string.

function getFormAsString(formName){

//Setup the return String


returnString ="";

//Get the form values


formElements=document.forms[formName].elements;

//loop through the array , building up the url


//in the form /strutsaction.do&name=value

for ( var i=formElements.length-1; i>=0; --i ){


//we escape (encode) each value
if(formElements[i].type != "radio" || formElements[i].checked) {
returnString=returnString+"&"+escape(formElements[i].name)
+"="+escape(formElements[i].value);
}
}

//return the values


return returnString;
}
o Very nice...small change required
2005-10-27 09:58:38 paulbrowne [Reply | View]

Thanks for the update to the Javascript. I am sure there are many other enahancements that can be included to
improve the samples given for your particular applications!
 Very nice...small change required
2006-10-16 21:44:47 erichein [Reply | View]

This method also needs to handle check boxes:

function getFormAsString(formName){

//Setup the return String


returnString ="";

//Get the form values


formElements=document.forms[formName].elements;

//loop through the array , building up the url


//in the form /strutsaction.do&name=value

for ( var i=formElements.length-1; i>=0; --i ){


//we escape (encode) each value
if((formElements[i].type != "radio" && formElements[i].type != "checkbox") || formElements[i].checked) {
returnString=returnString+"&"+escape(formElements[i].name)+"="+escape(formElements[i].value);
}
}

//return the values


return returnString;
}
• DWR does work with Struts
2005-10-27 08:26:33 joe_walker [Reply | View]

It's not true to say that DWR conflicts with struts. In DWR version 1.0 the 2 sit alongside each other quite nicely.

In DWR 1.1 there is even a StrutsCreator that makes the integration easier.

o DWR does work with Struts


2005-11-03 11:54:03 lhbarbier [Reply | View]

I´m interesing an using DWR with struts, when liberate DWR 1.1 or where obtain StrutsCreator?

Thank´s
o DWR does work with Struts
2005-10-27 09:57:38 paulbrowne [Reply | View]

I think DWR (Direct Web Remoting) is a very good framework and the article actually recommends it for certain
situations.

For other situations (e.g. where you have an existing Struts application) and do not / cannot introduce another
framework , then the method in this article is ideal.

Вам также может понравиться