MSc-IT Study Material
June 2010 Edition

Computer Science Department, University of Cape Town

Getting data from a server

Our previous examples have all only read data from a file on your computer. However, AJAX is typically used to read files off of a Web server. The only substantial difference is that the a Web server will return a response status other than 0 (typically, if you recall from the previous chapter, the value 200), which is what we have been testing for in the examples.

This example will make use of the Tomcat Web server from the previous chapter. Create a directory in the Tomcat webapps subdirectory titled “random”. The first thing that we will work on is a simple Servlet that will return random numbers, using Java Random objects. In the classes directory, add the class for this Java file:

import java.io.*; 
import javax.servlet.*; 
import javax.servlet.http.*; 
import java.util.Random; 

public class RandomServlet extends HttpServlet { 

    public void doGet(HttpServletRequest request, 
		      HttpServletResponse response) 
    { 
	try { 
	    PrintWriter out = response.getWriter(); 
	    out.println((new Random()).nextInt()); 
	} 
	catch (IOException e) { 
	    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); 
	} 
    } 
}
    

The RandomServlet class merely instantiates the Random class, and returns the next random integer. It also handles any errors.

The appropriate web.xml file (added, as you can recall, to the WEB-INF directory), is:

<?xml version="1.0"?> 

<!DOCTYPE web-app 
    PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" 
    "http://java.sun.com/dtd/web-app_2_3.dtd"> 

<web-app> 
  <display-name>Random Numbers</display-name> 
  <description> 
    Returns random numbers 
  </description> 

  <servlet> 
    <servlet-name>RandomServlet</servlet-name> 
    <description> 
      A simple servlet that returns HTML fragments of random numbers. 
    </description> 

    <servlet-class>RandomServlet</servlet-class> 
  </servlet> 

  <servlet-mapping> 
    <servlet-name>RandomServlet</servlet-name> 
    <url-pattern>/random</url-pattern> 
  </servlet-mapping> 
</web-app>
    

You can test this Web application by starting Tomcat and visiting the URL: http://localhost:8080/random/random

The AJAX portion of this example is the index.html file, which should be added directly into the random directory:

<html> 
  <head> 
    <title>Press a button to get a number!</title> 

  </head> 
  <body> 
    <script type="text/javascript"> 

      function create_request() { 
         var httpRequest; 
         if (window.XMLHttpRequest) { 
            httpRequest = new XMLHttpRequest(); 
         } 
         else if (window.ActiveXObject) { 
            httpRequest = new ActiveXObject("Microsoft.XMLHTTP"); 
         } 
         else 
         { 
            document.write("Unable to create XMLHttpRequest object."); 
         } 

         return httpRequest; 
      } 

      function get_data_synchronously_from(url_name) 
      { 
        var httpRequest = create_request(); 

        httpRequest.open("GET", url_name, false); 
        httpRequest.send(null); 
        if (httpRequest.status != 200) // For non http requests. 
        { 
          alert("There has been an error reading the URL."); 
          return null; 
        } 
        else 
        { 
          return httpRequest.responseText 
        } 
      } 

      function button_press() 
      { 
	document.getElementById("display-div").innerHTML= get_data_synchronously_from("http://localhost:8080/random/random"); 
      } 

    </script> 

	<h1> Random numbers from the server: </h1> 
 	<form> 
      		<input type="button" value="Print a number!" onclick="button_press();"/> 
    	</form> 
	<div id="display-div"> 
		<p>The button hasn't yet been pressed.</p> 
	</div> 
    
  </body> 
</html>
    

This file is very similar to the previous example. Notice that get_data_synchronously_from() has been updated to retrieve data from an URL. Importantly, the status of the response object now returns the value 200 when the the HTTP request has been successful.

Again, there is a DIV tag with an ID whose data is replaced with the random number. The random number obtained from the RandomServlet we previously wrote.

Play with this application. You will see that the random number is always updated without reloading the page. Also notice that no matter what random number is displayed on the page, if you ask the browser to show you the page's source, you will never find the number in the source. This is because the Web page is always being dynamically updated.