AJAX with Java

As a major requirement for AJAX application from server side language is to retrieve the request from client side and then parse it based on the format of the request. The request can be in form of a simple string, or XML, or JSON. And similarly the AJAX application expects a response back from server in one of these formats. Java can fulfill these requirements easily.

As for the first part, the server side language needs to accept the request from AJAX application in client side. Now Java has multiple ways to accept the request like JSPs, Servlets, Struts, JSFs etc. lets take a Servlet example

Public void doGet(HttpServletRequest req, HttpServletResponse res)
{
String ajaxData=req.getParameter(“Data”);
String returnString = executeAJAXRequest(ajaxData);
res.setContentType(“text/xml”);
res.getWriter.write(returnString);
}

Above one is a simple example. I left some of the details on purpose. Like what is executeAJAXRequest method doing. This will actually depend on the kind of request we receive.

The request might be a text based one where we don’t need to do any special parsing.

String executeAJAXRequest(String name)
{
String helloString= “Hello “+name;
return helloString;
}

That’s just a simple example; we could be doing some database operations in the method based on the name we got. But the idea is that the data is being used as it is. If it was a number say employee number we would convert to long and use.

Now if the data is in XML format. We already know that Java has strong XML support. It can parse and create XML documents easily using either DOM or SAX parsers. The following example shows how to parse data (uses apache’s xerces library)

ajaxRequest=”<employees><employee><name>John</name></employee></employees>”;

ArrayList executeAJAXRequest(String ajaxRequest)
{
ArrayList<String> nameValueArray=new ArrayList<String>(10);
try
{
DOMParser parser = new DOMParser();

parser.parse(new org.xml.sax.InputSource(new java.io.StringReader(ajaxRequest)));
DocumentImpl document = (DocumentImpl)parser.getDocument();

//get the root of the XML document
Node root = document.getFirstChild();
NodeList childNodes=root.getChildNodes();

for(int i=0;i<childNodes.getLength();i++)
{
nameValueArray.add(i, childNodes.item(i).getFirstChild().getFirstChild().getNodeValue());
}
}
catch (SAXException e)
{
e.printStackTrace();
//handle exception
}
catch(IOException e)
{
e.printStackTrace();
//handle exception
}

return nameValueArray;
}

The third way to pass data from client to server and vice versa is by using JSON. There are many libraries available in Java to parse and create JSON strings. Here is an example of code parsing a JSON String from client side using json-simple library (http://code.google.com/p/json-simple )

JSON string received from client is something like “{\”Employee\”: [{\”name\”: \”Eric\”, \”EmployeeNum\”: \”1232\”, \”Designation\”: \”SE\”}]}”

void executeAJAXRequest(String ajaxRequest)
{
JSONParser jsonParser = new JSONParser();
ContainerFactory containerFactory = new ContainerFactory(){

public List creatArrayContainer() {
//Add Details if required
return null;
}

public Map createObjectContainer() {
//Add Details if required
return null;
}
};

try{
Map jsonMap1 = (Map)jsonParser.parse(ajaxRequest, containerFactory);

Iterator iter1 = jsonMap1.entrySet().iterator();
while(iter1.hasNext()){
Map.Entry entry1 = (Map.Entry)iter1.next();
String valueString=entry1.getValue().toString();
String dataString=valueString.substring(1,valueString.length()-1);

Map jsonMap2 = (Map)jsonParser.parse(dataString, containerFactory);

Iterator iter2 = jsonMap2.entrySet().iterator();
System.out.println(“Here are the Employee Details”);
while(iter2.hasNext()){
Map.Entry entry2 = (Map.Entry)iter2.next();
System.out.println(entry2.getKey() + “=>” + entry2.getValue());
}
}

}
catch(ParseException pe){
System.out.println(pe);
}
}