JSON Interchange Using AJAX and Java Servlets

The following is a simple example of how to implement a JSON based data interchange using an AJAX client-side request and a Java Servlet server-side response. The expected outcome of the example code is that an individual’s full name is displayed after the client enters a user ID.

On the client-side, we need a web page with an input field to capture the user ID (user_id) and a placeholder to display the returned full name (user_name).

We need to load the jQuery library to be able to use some of the nice AJAX functionality.

We also need a JavaScript function on the client-side to generate the XMLHttpRequest. The following jQuery based function will generate the XMLHttpRequest when the user_id input field changes. When the user changes the contents of the input field, this function is called and a request is then submitted to the server-side Java Servlet (FullNamePopulator). The JSON based response from the Java Servlet is then parsed by the function and the user_name placeholder is replaced with the returned full name.

The Java Servlet is expected to return a JSON formatted response as follows given an input user_id of “abc.”

The Java Servlet handles the look up and formatting of the response. In this example, a simple HashMap is used to hold three sample user ID’s and the associated full names. The user_id submitted to the Servlet is used as a key to the HashMap. If a value is found, then the full name is used otherwise “Unknown User” is used and the JSON response is formatted and sent to the client.

Leave a Comment