Sunday, 31 October 2010

Ajax XML response and Struts2

Ajax and Struts2 are really cool! I really enjoy combining these two together in my web applications.
Few days ago I was working on some application, and needed to update some values in my JSP using Ajax. I decided to use XML as an Ajax response, parse it and do whatever I want with it...

In this post I will show you how to make Struts2 return XML as an Ajax response.

Here is an example of how you can do this:

public class CustomAction extends ActionSupport
{

public HttpServletResponse getResponse() 
{
        return ServletActionContext.getResponse();
}

@Override
    public String execute() throws Exception {
        PrintWriter printWriter = null;
        getResponse().setContentType("text / xml;charset = UTF-8");
        getResponse().setHeader("Cache - Control", "no - cache");
        
        StringBuffer sb = new StringBuffer("");
        // let's say you have A Movie object "movie" that needs to be represented as XML
try
        {
            printWriter = getResponse().getWriter();
            sb.append("" + movie.getDirector() + "");
            sb.append("" + movie.getLanguage() + "");
            sb.append("" + movie.getYear() + "");
            sb.append("");
            printWriter.print(sb.toString());
        }
        catch (IOException e)
        {
            e.printStackTrace();
            throw e;
        }
        finally
        {
            printWriter.close();
            printWriter = null;
        }
        return NONE;
    }

} 

And that's it! Just create a PrintWriter, adjust some values in response and print your XML.

And now, in your JavaScript, you can parse this xml and do something with it:

directors=xmlhttp.responseXML.documentElement.getElementsByTagName("director");
        languages=xmlhttp.responseXML.documentElement.getElementsByTagName("language");
        years = xmlhttp.responseXML.documentElement.getElementsByTagName("year");
        director = directors[0].firstChild.nodeValue;
        language = languages[0].firstChild.nodeValue;
        year = years[0].firstChild.nodeValue;
document.getElementById('director').value=director;
document.getElementById('language').value=language;
document.getElementById('year').value=year;

That's it.
I hope I helped someone...