Getting Started with AJAX using Java

21/07/2010

AJAX is an acronym for Asynchronous JavaScript And XML. AJAX provides an ability to communicate with the server asynchronously. Here asynchronous is the keyword. To explain that in simple terms, you can send a request to server and continue user interaction with the user. You need not wait for response from the server. Once the response arrives, a designated area in UI will update itself and reflect the response information. Whole page need not be reloaded.

This is achieved by AJAX using XMLHttpRequest object. Your browser provides the capability for XMLHttpRequest object. Most modern browsers provides support for XMLHttpRequest. This object helps for http request and process XML response. It is not mandatory that you should use only XML. Simple text can also be used in Ajax but which is uncommon.

Before continuing with the article, I assume that you have basic knowledge about http headers, request response mechanism, different method types and response codes. If you lack knowledge in these areas, it is better to update them before proceeding. If you cant read GET, POST, HTTP status 200 OK and response Content-Type: text/html, xml then you must know these topics before learning AJAX. I am not writing in detail about them here, because each one of them calls for a detailed separate article.

Let me write a HelloWorld ajax web application to demonstrate basics. We shall have a button with name ‘Say Hello!’ On click of that button, without reloading the whole page we will display “Hello World!” by replacing the ‘Say Hello!’ button. Following source code listing contains complete code of sample web application.

index.jsp

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<title>Getting Started with AJAX using JAVA</title>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<script type="text/javascript" language="javascript" src="ajax.js"></script>
</head>
<body>
	<div>Getting Started with AJAX using JAVA: Hello World!</div>
	<div id="hello"><button type="button" onclick="makeRequest()">Say Hello!</button></div>
</body>
</html>

index.jsp contains a div ‘hello’. That is the div which XMLHttpRequest object is going to overwrite with response from Servlet. On click of the button we call a java script function makeRequest(). Until now, there is nothing special. Its usual jsp and javascript call. Ajax is not in the picture.

Now go through makeRequest() given below. Inside that we call getXMLHttpRequest() which returns a XMLHttpRequest object. That can be used as a utility method in all your AJAX programs. Thats an attempt to standardization. Different versions of browsers provide different ways of creating XMLHttpRequest. We are covering all possible combinations inside that method.

Once we get XMLHttpRequest object, we need to register a function which will be called on state change. Now its time to explain in detail about XMLHttpRequest object.

XMLHttpRequest properties and events

XMLHttpRequest consists of properties readyState, status, statusText, responseText and responseXML.

  • readyState denotes states as 0 – UNINITIALIZED, 1 – LOADING, 2 – LOADED, 3 – INTERACTIVE, 4 – COMPLETE.
  • status is HTTP status code for the response
  • statusText is HTTP status message for the status code
  • responseText is response text from server
  • responseXML is DOM document object of reponse XML document from server

XMLHttpRequest contains an event ‘onreadystatechange’. It is invoked whenever ‘readyState’ property given above changes.

We need to register a function for the above event ‘onreadystatechange’. In our makeRequest(), after getting xmlHttpRequest object we register getReadyStateHandler(xmlHttpRequest). Therefore whenever there is a state change, this function will be called by the XMLHttpRequest / browser.

After registering the callback funtion we set the request url as the HelloWorld servlet. In web.xml we have done the servlet mapping for that servlet.

In getReadyStateHandler function, if readyState is 4 and http status code is 200 then we set the reponse text from XMLHttpRequest object to the div hello in index.jsp.

ajax.js

/*
 * creates a new XMLHttpRequest object which is the backbone of AJAX,
 * or returns false if the browser doesn't support it
 */
function getXMLHttpRequest() {
	var xmlHttpReq = false;
	// to create XMLHttpRequest object in non-Microsoft browsers
	if (window.XMLHttpRequest) {
		xmlHttpReq = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		try {
			// to create XMLHttpRequest object in later versions
			// of Internet Explorer
			xmlHttpReq = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (exp1) {
			try {
				// to create XMLHttpRequest object in older versions
				// of Internet Explorer
				xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (exp2) {
				xmlHttpReq = false;
			}
		}
	}
	return xmlHttpReq;
}
/*
 * AJAX call starts with this function
 */
function makeRequest() {
	var xmlHttpRequest = getXMLHttpRequest();
	xmlHttpRequest.onreadystatechange = getReadyStateHandler(xmlHttpRequest);
	xmlHttpRequest.open("POST", "helloWorld.do", true);
	xmlHttpRequest.setRequestHeader("Content-Type",
			"application/x-www-form-urlencoded");
	xmlHttpRequest.send(null);
}

/*
 * Returns a function that waits for the state change in XMLHttpRequest
 */
function getReadyStateHandler(xmlHttpRequest) {

	// an anonymous function returned
	// it listens to the XMLHttpRequest instance
	return function() {
		if (xmlHttpRequest.readyState == 4) {
			if (xmlHttpRequest.status == 200) {
				document.getElementById("hello").innerHTML = xmlHttpRequest.responseText;
			} else {
				alert("HTTP error " + xmlHttpRequest.status + ": " + xmlHttpRequest.statusText);
			}
		}
	};
}

A simple Hello World servet sending response as Hello World! as text.

HelloWorld.java

package com.javapapers.sample.ajax;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HelloWorld extends HttpServlet {

	/**
	 * A simple HelloWorld Servlet
	 */
	public void doPost(HttpServletRequest req, HttpServletResponse res)
			throws java.io.IOException {
		res.setContentType("text/html");
		res.getWriter().write("Hello World!");
	}

	public void doGet(HttpServletRequest req, HttpServletResponse res)
			throws java.io.IOException {
		doPost(req, res);
	}
}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>Getting Started with AJAX using JAVA</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>helloWorld</servlet-name>
    <servlet-class>com.javapapers.sample.ajax.HelloWorld</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>helloWorld</servlet-name>
    <url-pattern>/helloWorld.do</url-pattern>
  </servlet-mapping>
</web-app>

Output of Hello World AJAX

Before AJAX call:

After AJAX call:

I have used text response to demonstrate AJAX. There is a lot more to AJAX. I will get into using XML, advanced techniques and jquery in future articles.

Great!
Such a short and simple example to understand AJAX :)

Praveen Kumar Jayaram on July 22nd, 2010 6:35 am

[...] ingressaram no Java tendo a tecnologia AJAX sendo 100% encapsulada por outras. Segue um ótimo tutorial de AJAX escrito por Joseph [...]

AJAX com Java « Fer&hellip on July 23rd, 2010 11:50 am

thanks for posting

Anonymous on July 23rd, 2010 7:11 pm

Good article. It is very stright forward and no mess in explaination.

Please post the article on AJAX with XML as one example and JQuery.

Thanks
Anand Garlapati

Anand Garlapati on July 24th, 2010 5:38 am

It was Kindly Helpful. Thank u

Nalini on August 12th, 2010 1:11 pm

Good Artical and helpful for beginners!!!

Shalini Gupta on August 13th, 2010 6:09 pm

great! very simple, and the base to understand the use of complex frameworks!

Juanje on September 17th, 2010 7:00 am

Very Good Example with explaination.

Dnyaneshwar on October 27th, 2010 6:27 am

Thanks a lot! I wasted a lot of time to run hello ajax using java until i found this one.God Bless U! Keep Helping!!!!!!

Vijay on November 24th, 2010 11:23 am

HI,

I don’t have any server to execute the above program.If I execute it,am getting alert with “Http Error 2:Unknown” Is it possible to execute in my local system without any server.

Regards
Ramesh

Ram on December 6th, 2010 12:20 pm

Hi,

I too prefer to use jquery.

MArco on February 24th, 2011 11:38 am

Nice one. Also Please explain JSON with AJAX

subbu on March 5th, 2011 3:21 am

how to make calculator using ajax?
uk essay help

james on March 8th, 2011 6:20 pm

superb

Anto on March 15th, 2011 9:33 am

Great tutorial! I was trying a different tutorial (found here http://www.hiteshagrawal.com/ajax/ajax-programming-with-jsp-and-servlets) and they failed to mention updating the web.xml file. Your tutorial is much better thank you!

Lino on April 14th, 2011 4:37 pm

paal site

uiu on April 20th, 2011 3:17 pm

Nice tutorial ..very helpful

Prasanna on April 29th, 2011 8:21 am

Hi,
I have three jsp pages.
in first jsp page i have one add button when this is clicked i made a call to ajax function
now the ajax is called and kept the contents in first jsp
now the contents which are added are one select list and textfield
now when i click the select list which was added again i have to call ajax and should keep the contents of third jsp..
is it possible to call ajax like this
pls reply me………

swathi on May 6th, 2011 7:33 am

I Love this Example… It Was Simply Superb..Explaining the whole flow in a single basic example, it was really good one….!!!!

Hey Can u Just Help me in drag and drop events in ajax, I need to create a form builder in java by using ajax, Can i expect good examples on that… Waiting for your reply… :-)

Naresh on May 6th, 2011 1:50 pm

This ajax tutorial really simple and superb. Keep it up

Ragu` on May 19th, 2011 9:31 am

Lots of thanks for u, such a great example.

Somdev on June 15th, 2011 8:41 am

El mejor ejemplo para empexar con ajax que he visto en la red

Miguel Angel on June 15th, 2011 2:21 pm

[...] Continue reading here: Getting Started with AJAX using Java [...]

Getting Started with AJAX&hellip on June 20th, 2011 9:06 pm

HI,

im getting HTTP ERROR 404:

WHILE excecute above prgm.. plz help me

showni on June 23rd, 2011 10:43 am

Hi,

Nice one,i understood the basic working of Ajax,i need some complicated examples……..

thanks a lot for giving this article….

prabhu on September 15th, 2011 7:02 am

thanks 4 the description

jyoti on October 17th, 2011 8:27 am

hi,
I tried this above example, but im getting two errors “XMLHttpRequest cannot be resolved to a type” and “ActiveXObject cannot be resolved to a type”..

Plz provide solution for this…

Thanks,
srinivas G.

srinivas on October 22nd, 2011 7:30 am

Hi sir,
your website helped me to do lot of works in my firm,
now i need a help from you, i am creating a web application like facebook sharing proceess with java and oracle.
So i need some help from you, how to make the sharing process?

Thanking you.

Randeep on November 16th, 2011 7:15 am

your article is very good.it help me alot.

jyoti on November 17th, 2011 3:41 pm

simple but too good

Manoj on January 6th, 2012 7:22 am

Excellent Sir. We have learnt a lot from this tutorial.

Rajesh Takkellapati on January 20th, 2012 11:31 am

super sir,i has learn more information your blog

s.nagachary on January 29th, 2012 4:09 pm

thanks a lot! really useful :)

Anonymous on January 30th, 2012 7:20 pm

Hi,
I want to ask how to send parameters to .java file thorugh ajax call?

Thanks :)

Tejali on February 2nd, 2012 6:40 pm

Neat & Clean in each & every post.. i went through more than half of your posts until just never get that much info on a single site..

Please post regarding Jquery & Spring Framework also.

Anil on February 3rd, 2012 1:50 pm


Email:

about
I am Joe, author of this blog. I run this with loads of passion. If you are into java, you may find lot of interesting things around ...more about me. Google+
java badge
Home