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 result 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
).
User ID: <input type='text' name='user_id' id='user_id' />
<span id="user_name"></span>
We need to load the jQuery library to be able to use some of the nice AJAX functionality.
<script src="https://code.jquery.com/jquery-latest.min.js"></script>
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.
$(function() { $("input#user_id").change(function() { $.getJSON("/FullNamePopulator",{user_id: $(this).val()}, function(j) { var value = ''; for (var i = 0; i < j.length; i++) { value = j[i].optionDisplay; } $("#user_name").html(value); }) }) });
The Java Servlet is expected to return a JSON formatted response as follows given an input user_id
of “abc.”
[{"optionValue":"abc","optionDisplay":"Full Name 1"}]
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.
import java.io.IOException; import java.util.HashMap; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class FullNamePopulatorServlet extends HttpServlet { private static final long serialVersionUID = 1L; public void init(ServletConfig config) throws ServletException { super.init(config); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletOutputStream outputStream = null; String userID = null; String userName = null; StringBuffer outputStringBuffer = new StringBuffer(); HashMap exampleHashMap = new HashMap(); exampleHashMap.put("abc", "Full Name 1"); exampleHashMap.put("xyz", "Full Name 2"); exampleHashMap.put("123", "Full Name 3"); try { response.reset(); response.setHeader("Pragma", "no-cache"); response.setDateHeader("Expires", -1); response.setContentType("text/html"); if (request != null) { userID = request.getParameter("user_id"); } if ((userID == null) || (userID.trim().equals(""))) { userID = ""; } if (exampleHashMap.containsKey(userID)) { userName = (String) exampleHashMap.get(userID); } else { userName = "Unknown User"; } outputStream = response.getOutputStream(); outputStringBuffer.append("[{\"optionValue\":\"") .append(userID) .append("\",\"optionDisplay\":\"") .append(userName) .append("\"}]"); outputStream.print(outputStringBuffer.toString()); } catch (Exception e) { } finally { } return; } public void destroy() { return; } }