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;
xhr.send(null);

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


If you enjoy this Java programming article, please share with friends and colleagues. Follow the author on Twitter for the latest news and rants.

Editorial page content written by Neil Coffey. Copyright © Javamex UK 2021. All rights reserved.