Академический Документы
Профессиональный Документы
Культура Документы
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).
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.
• 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.
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.
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:
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
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!
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.
To use, simply add the retrieveURL() function to the onclick()/onChange() method of the event you wish to
trigger the screen update.
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) {
// 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
function getFormAsString(formName){
•
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
} else {
alert("Problem with server response:\n "
+ req.statusText);
}
}
}
function replaceExistingWithNewHtml
(newTextElements){
function splitTextIntoSpan(textToSplit){
• 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.
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:
…….
…….
</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.
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.
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);
}
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.
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?
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
%>
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){
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]
function uncache(url,form){
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!
retrieveURL("roomBookingAction.do?ask=COMMAND1","roomBookingBean");
<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.
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!
retrieveURL("roomBookingAction.do?ask=COMMAND1","roomBookingBean");
<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
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]
Put this after the open statement and it might work out for you too.
Have you tried any or all of the following to debug the code and see the request that is being attempted to be
sent?
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
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?'
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
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]
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"
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
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:
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).
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.
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).
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!
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:
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]
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.
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]
onchange="retrieveURL('/strutajax/buscarProducto.do,'categoriaForm');"
1) Are you surrounding the sections to be changed with <span id="somename"> ... html select here ...
</span>?
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]
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
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.
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.
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]
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]
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,
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.
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
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.
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]
http://ajaxanywhere.sourceforge.net
o reinventing a wheel?
2005-11-01 01:51:39 paulbrowne [Reply | View]
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]
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]
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){
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]
function getFormAsString(formName){
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.
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.