AJAX programming: server-side Java

A simple option for handling the AJAX request on the server is to use a Java Servlet. In fact, be it in Java or otherwise, handling a request from an XMLHttpRequest isn't terribly different from handling a bog standard HTTP request. About the only differences are that we are likely to want to parse and return data in XML format.

Reading data from the client

There are two common schemes for reading any request data sent by the client. If the client has sent the data as a URL parameter, then we use the getParameter() method. For example, if the client sends a parameter called text as follows:

xhr.open("GET", "/ajaxservice?text=" + text);
xhr.onreadystatechange = processFunction;

then on the server, we can read the parameter from our Servlet as follows:

public class AjaxServlet extends HttpServlet {
  public void doGet(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {
    String text = req.getParameter("text");

Sending data back to the client