Chapter 3. A Simple Ajax Servlet

In the previous chapter, we wrote a JavaScript/HTML client for a system that converts keystrokes to the corresponding decimal values. Now we need to focus on the backend: the Java servlet that provides the client with the information it needs. The XMLHTTPRequest( ) function in the client sends a request out into the ether; it doesn’t care what kind of server replies. The response can come from a PHP server, a .NET server, a server hosting Ruby on Rails, a Java server, and so on. Any server that can receive an HTTPRequest and respond with an HTTPResponse will do.

Since this is a book for Java developers, we’ll create a servlet that intercepts the request, converts the keystroke into its decimal representation, and sends the resulting data back to the client.

The first version of our servlet is very simple: it computes a single result (the value of the keystroke in decimal) and sends it back to the client. The complete servlet code is presented in Example 3-1.

Example 3-1. The AjaxResponseServlet

/* * Converts a character to decimal and sends back the * value in the response. */ package com.oreilly.ajax.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class AjaxResponseServlet extends HttpServlet { private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest req, HttpServletResponse ...

Get Ajax on Java now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.