Introduction
Found myself with some spare time on my hands and decided to figure out how Ajax works and develop a little example for the blog seeing that I haven’t updated since near infinity in Internet time.
Ajax
Ajax (AJAX) stands for Asynchronous JavaScript and XML. It is a technique using JavaScript and server objects to change webpage content only for a specific piece of the webpage without refreshing the whole page. This is different from normal JavaScript because the change includes an exchange of data with the server. This allows access to services that are found on a server like databases and business logic. Users have an experience that is more interactive. A good example would be a series of pictures being displayed that are only accessible from a database. Each time a picture is clicked it changes to a new picture.
An Ajax request has two major parts, the request and the interactive server portion that hands out the data the request wants. The request creates a XMLHttpRequest and sends the request as a standard html post or get. The server responds in kind with XML. If done right, this draws a hard line between the presentation layer and the business layer. This is not a new idea. JSPs have backing beans. Thick clients have remote objects (RMI anyone?). Ajax in my opinion goes farther by removing the need for a specific type of server side support it needs. It doesn’t care if it is PHP or a Servlet. All it cares for is the contract to be fulfilled. This creates a situation where the implementation of the server objects can change completely and the webpage won’t care. That’s right, one day a bunch of server scripts can be used and then six months later, a set of servlets can be used to replace them. That is an extreme example because of having to stand up a web container in place of the server that supports scripts but a lot of the mapping requests to the server can be done rather painlessly using servlet mapping.
Example
Let’s get to an example of Ajax in action. This example updates three fields with the time from different time zones. The first one is local time, the second is GMT and the last time is for New York. I am using a JavaScript library named jQuery to help write the JavaScript and the Ajax request. For more information on jQuery, go to http://jquery.com/. Since this is a Java blog, the server object is a servlet named TimeServlet.java. All the code can be downloaded from https://github.com/darylmathison/time-ajax-example. The example was created in Eclipse so Eclipse users can import it as a project. The web container I used is a Tomcat 5.5 server.
Webpage
Here is the webpage that makes the requests to the server object. It puts the current time from three different time zones into an html table beneath the label of the time zone it represents. The current time is displayed every time the “Show Times” button is clicked.
<html>
<head>
<meta http-equiv=“Content-Type” content=“text/html; charset=ISO-8859-1”>
<title>AJAX Timetitle>
<script type=“text/javascript” src=“jquery.js”>script>
<script type=“text/javascript”>
$(document).ready(function() {
var timeid = “timeid”;
$(“#timebutton”).click(function() {
$(“#local”).load(‘/TimeAjax/TimeServlet’, {timeid: “local”});
$(“#GMT”).load(“/TimeAjax/TimeServlet”, {timeid: “GMT”});
$(“#newyork”).load(“/TimeAjax/TimeServlet”, {timeid: “newyork”});
});
$(“#errorMsg”).ajaxError(function(event, request, settings, error){
$(this).append(“ajax call failed: “ + settings.url);
alert(settings.url);
});
});
script>
head>
<body>
<table>
<tr>
<td>Local Timetd>
<td>GMT Timetd>
<td>New York Timetd>
tr>
<tr>
<td><span id=“local”> span>td>
<td><span id=“GMT”> span>td>
<td><span id=“newyork”> span>td>
tr>
<tr>
<td colspan=“3”><div id=“errorMsg”>div>td>
tr>
table>
<button id=“timebutton”>Show Timesbutton>
body>
html>
The load function is where the actual request happens.
$(“#local”).load(‘/TimeAjax/TimeServlet’, {timeid: “local”});
$(“#GMT”).load(“/TimeAjax/TimeServlet”, {timeid: “GMT”});
$(“#newyork”).load(“/TimeAjax/TimeServlet”, {timeid: “newyork”});
This is a series of requests for items that have the id of local, GMT and newyork respectively. They all call the servlet with different timeids to tell the servlet what time zone to display back. These requests are sent out when the “Show Times” button is clicked.
<td><span id=“local”> span>td>
<td><span id=“GMT”> span>td>
<td><span id=“newyork”> span>td>
These are the three table cells that are going to be changed when the responses come back.
Servlet
Here is the code for the TimeServlet that services the requests from the webpage. It grabs the timeid from the request and uses java.text.SimpleDateFormat to format the current time into the respective time zone.
public class TimeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* Default constructor.
*/
public TimeServlet() {
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String timeid = request.getParameter(“timeid”);
System.out.println(“timeid is “ + timeid);
if (timeid != null && timeid.length() > 0 ) {
response.setContentType(“text/xml”);
response.setHeader(“Cache-Control”, “no-cache”);
Calendar cal = null;
String dateformat = “HH:mm”;
SimpleDateFormat format = null;
if (“local”.equals(timeid)) {
System.out.println(“in local”);
cal = Calendar.getInstance();
format = new SimpleDateFormat(dateformat);
response.getWriter().write(“” +
format.format(cal.getTime())+ “”);
} else if(“GMT”.equals(timeid)) {
cal = Calendar.getInstance();
format = new SimpleDateFormat(dateformat);
format.setTimeZone(TimeZone.getTimeZone(“GMT”));
response.getWriter().write(“” + format.format(cal.getTime()) + “”);
} else if(“newyork”.equals(timeid)) {
TimeZone tz = TimeZone.getTimeZone(“America/New_York”);
cal = Calendar.getInstance();
format = new SimpleDateFormat(dateformat);
format.setTimeZone(tz);
response.getWriter().write(“” + format.format(cal.getTime())+ “”);
} else {
response.getWriter().write(“cannot find timeid”);
}
} else {
response.getWriter().write(“there is no timeid”);
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
The real work happens in the doGet method.
String timeid = request.getParameter(“timeid”);
Here is where the timeid passed from the Ajax request is pulled from the HttpServletRequest. The passed timeid variable is tested for validity to ward off any NullPointerExceptions.
The below code details what I did to display the time for the local time zone.
if (“local”.equals(timeid)) {
System.out.println(“in local”);
cal = Calendar.getInstance();
format = new SimpleDateFormat(dateformat);
response.getWriter().write(“” + format.format(cal.getTime())+ “”);
}
This is easy because Java defaults to the local locale and time zone. It gets trickier for GMT and the New York time zones but not too much because all that needs to happen is setting the time zone of the formatter.
else if(“GMT”.equals(timeid)) {
cal = Calendar.getInstance();
format = new SimpleDateFormat(dateformat);
format.setTimeZone(TimeZone.getTimeZone(“GMT”));
response.getWriter().write(“” + format.format(cal.getTime()) + “”);
}
This is repeated for the New York time zone using the “America/New_York” time zone.
Last Thoughts
This is another tool in the toolbox for web development. It allows web components to be more interactive enhancing the user experience on your website. It can also be used to further separate presentation and business logic. If you have any comments or questions about this post, please leave them below.