Tuesday, November 1, 2011

Ajax in Strut 2 using XmlHTTPRequest

Ajax with Struts 2, I think I have had a good start with Struts 2. I was just toying around with what was provided in vaannila. It’s a real good stuff and in no time I got this idea of trying AJAX with Struts 2.

It took me some time though to understand how stuffs work with Struts.

Following is the fragment of struts.xml file that did the trick for me at last

            <action name="AjaxTest"  class="AjaxTest">
                     <result type="stream">
                           <param name="contentType">text/html</param>
                           <param name="inputName">inputStream</param>

The class I Used to output the response is as follows

import java.io.InputStream;
import java.io.StringBufferInputStream;
import com.opensymphony.xwork2.ActionSupport;

public class AjaxTest extends ActionSupport  {
    private InputStream inputStream;
    public InputStream getInputStream() {
        return inputStream;

    public String execute() throws Exception {
        inputStream = new StringBufferInputStream("Hello World! This is a text string response from a Struts 2 Action.");
        return SUCCESS;

The javascript I used to perform the AjaxRequest is as follows
function triggerAjaxForExperiment()      {
       xmlHttp=new AjaxProcess("http://localhost:8080/myNewHelloWorld/AjaxTest.action",false);
       //initiate and asynchronous request to check whether the current reporthas any open chid documents

       //this results in a boolean object isChildActive which is either true or false

About the AjaxProcess function that I have used here, it is a custom API I have created and can be found in the following location

And to your jsp file add the following line of html code to perform the test

       <input type="button" value="Ajax Experiment" onclick="triggerAjaxForExperiment()"/>

In the end what I got was as follows

It feels good to me J

Hope this helps you as well J

No comments:

Post a Comment