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 res)             throws ServletException, IOException {         String key = req.getParameter("key");         if (key != null) {             // extract the first character from key             // as an int, then convert that int to a String             int keychar = key.charAt(0);             String decimalString = Integer.toString(keychar);             // set up the response             res.setContentType("text/xml");             res.setHeader("Cache-Control", "no-cache");             // write out the response string             res.getWriter( ).write(decimalString);         }         else {             // if key comes back as a null, return a question mark             res.setContentType("text/xml");             res.setHeader("Cache-Control", "no-cache");             res.getWriter( ).write("?");         }     } } 

If you are experienced with servlets, you should understand what this code is doing. In case you haven't used servlets before, however, let's walk through the code.

The HTTP protocol allows the client and server to communicate with either a POST or a GET command. The GET command sends variables through the URL, as in http://localhost/application?name=steve. The POST command sends the data embedded in the client request.

For more information on the HTTP protocol, see Clinton Wong's HTTP Pocket Reference or HTTP: The Definitive Guide, by David Gourley et al. (both from O'Reilly).


When you write a servlet, you generally extend HttpServlet and override doGet( ), doPost( ), or both. Our client makes a simple GET request, so we only have to override one method:

 doGet(request,response) 

First we retrieve the key from the request:

 String key = req.getParameter("key"); 

Next we check whether the key is null; if it is not null, we can begin to operate on it. In this case, we get its decimal value:

 if (key != null) {     // extract the first character from key     // as an int, then convert that int to a String     int keychar = key.charAt(0);     String decimalString = Integer.toString(keychar); 

Once we have the decimal value of the key, we set up the response and send a string containing the code:

     // set up the response     res.setContentType("text/xml");     res.setHeader("Cache-Control", "no-cache");     // write out the response string     res.getWriter( ).write(decimalString); } 

Again, this should be very familiar if you've worked with servlets before. We set the content type, tell the browser not to use caching, and write the result (a String) to the output stream (a Writer) we get from the response. That's all there is to it!

Now let's create a web.xml deployment descriptor and write an Ant build file to compile and run the code. The web.xml file is presented in Example 3-2.

Example 3-2. web.xml

 <!DOCTYPE web-app     PUBLIC  "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"     "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd"> <web-app>     <servlet>         <servlet-name>AjaxResponseServlet</servlet-name>         <servlet-class>             com.AJAXbook.servlet.AjaxResponseServlet         </servlet-class>         <load-on-startup>1</load-on-startup>     </servlet>     <servlet-mapping>         <servlet-name>AjaxResponseServlet</servlet-name>         <url-pattern>/response</url-pattern>     </servlet-mapping>     <welcome-file-list>         <welcome-file>index.html</welcome-file>     </welcome-file-list> </web-app> 

There is only one servlet in this web application, the AjaxResponseServlet. That servlet is set to intercept requests at /response. The <servlet-mapping> in web.xml must match the url value in the convertToDecimal( ) function of index.html.

We'll place this web.xml file in the war/WEB-INF directory.




Ajax on Java
Ajax on Java
ISBN: 0596101872
EAN: 2147483647
Year: 2007
Pages: 78

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net