Thursday, July 17, 2008

AJAX and JSON

If we are using AJAX calls in our web pages it is difficult to process the response, which is coming from the server in xml format. Also it is difficult to create the response in xml format. One solution for this problem is the use of JSON format of communication between the client and server when we are using AJAX calls.

Before going to see the example we can see what is JSON format?

What is JSON format?
JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate.

For more information please visit

http://json-lib.sourceforge.net/index.html
http://www.json.org/java/

JAR files required:
commons-beanutils.jar
commons-collections-3.2.1.jar
commons-lang-2.4.jar
ezmorph-1.0.4.jar
json-lib-2.2.2-jdk15.jar
servlet-api.jar

Here we are going to implement an employee search web application. We have a list of employees, each of them have the properties name, employee id and department. For the time being this information are kept in a java List object.
Now in our application the user will be able to select one department and click on search. Then the lists of employees associated with the department are got listed in the table.
























Response in JSON format:[{"department":"HR","employeeId":"1002","name":"John"},{"department":"HR","employeeId":"1003","name":"Albert"},{"department":"HR","employeeId":"1008","name":"Thomas"}]


Employee class is given below.




EmployeeSearchBO class will initialize the list of Employee objects inside the static block.
findEmployeeByDepartment() will accept the department name as argument and will return the list of Employee objects belongs to that department.




We are separating the JSP and JS codes in separate files. EmployeeSearch.jsp will accept the department name for search.




EmployeeSearch.js will contain the methods to call the server using AJAX. It will send the department name as the search parameter to the server. From the server we will get the list of Employee objects in the format of JSON. The response will contain array of Employee objects. So we can iterate through the list and we can get each Employee object.




The servlet EmployeeSearchController will call the EmployeeSearchBO. findEmployeeByDepartment() to get the list of Employee objects. We are using JSONSearializer to convert the list object into JSON format. After that we are writing the same to response.




web.xml