MSc-IT Study Material
June 2010 Edition

Computer Science Department, University of Cape Town

Sending data to a server

For this example we will update the greetings Web application from the Web application chapter to use AJAX.

Create a new directory in webapps called “ajax-greetings”. We will use the following class, which you should compile and place in the classes directory:

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

public class ResponseServlet extends HttpServlet 
{ 
    public void doPost(HttpServletRequest request, 
		      HttpServletResponse response) 
    { 
	try { 

	    String name = request.getParameter("name"); 
	    PrintWriter out = response.getWriter(); 

	    if (name == null) { 
		out.println("No name has been given."); 
		return; 
	    } 

	    out.println(getGreeting() + name); 
	} 
	catch (IOException e) { 
	    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); 
	} 
    } 

    String getGreeting() 
    { 
	switch((new Random()).nextInt(5)) { 
	case 0: 
	    return "Hello, "; 
	case 1: 
	    return "Nice to meet you, "; 
	case 2: 
	    return "Hi, "; 
	case 3: 
	    return "Yo, "; 
	case 4: 
	    return "Hey, "; 
	} 

	return "Hello, "; 
    } 
}
    

This class accepts POST requests only. It is expecting to be passed the user's name in the “name” parameter, and then uses the getGreeting() method to find a random way of greeting the person. The Servlet then returns a single line, greeting the user.

The appropriate web.xml file 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>A Greetings Application</display-name> 
  <description>Asks the user's name and then greets them.</description> 

  <servlet> 
    <servlet-name>ResponseServlet</servlet-name> 
    <description>Performs the actual greeting.</description> 

    <servlet-class>ResponseServlet</servlet-class> 
  </servlet> 

  <servlet-mapping> 
    <servlet-name>ResponseServlet</servlet-name> 
    <url-pattern>/response</url-pattern> 
  </servlet-mapping> 
</web-app>
    

The index.html file, which should be placed directly in the ajax-greetings directory, follows:

<html> 
	<head> 
		<title>Some Greetings</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(file_url, variables) 
			{ 
				var httpRequest = create_request(); 

				httpRequest.open("POST", file_url, false); 
				httpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 
				httpRequest.send(variables); 
				if (httpRequest.status != 200) // For non http requests. 
				{ 
					alert("There has been an error reading the URL. " + httpRequest.status); 
					return null; 
				} 
				else 
				{ 
					return httpRequest.responseText 
				} 
			} 

			function button_press() 
			{ 
				document.getElementById("greeting-div").innerHTML= get_data_synchronously_from("http://localhost:8080/ajax-hello/response", "name=" + document.getElementsByName("user_name")[0].value); 
			} 
    		</script> 
		 
		<div id="greeting-div"> 
			What is your name?	 
		</div> 
		<form> 
			<input type="text" name="user_name"> 
			<input type="button" value="Say Hello!" onclick="button_press();"> 
  		</form> 
	</body> 
</html>
    

The page appears as before, with a text box for the user to enter their name and a button to press to return a greeting. The page displays this greeting in a DIV with an ID, which is how we have dynamically updated Web pages previously in this chapter. The bulk of the work is done in the get_data_synchronously_from() function, which has been updated to accept a second argument, “variables”. This is a list of data to be sent to the server, and is formatted as a list of names and their values: name=value&name2=value2&name3=value3 and so on. In this case, we only provide one name / value pair when calling this function. We do this in the button_press() function, which takes the value from the text box.

get_data_synchronously_from() also makes a call to setRequestHeader() to tell the server that data has been sent. If this call is not made, the server will ignore all data sent to it by this request. Next, variables is passed to the send function. The rest of the function operates exactly as before.

You can now test the application. You should notice that the Web application greets the user without reloading the page. The application also uses multiple, random greetings.