Wednesday, August 25, 2010

Simple Ajax using JSP tutorial

Ajax is the method of using Javascript, DHTML and the XMLHttpRequest object to perform a GET or POST and return a result without reloading the HTML page. Below is a very simple Ajax example using JSP.

To create first JSP page:
1. Download Eclipse IDE for Java EE Developers from
2. Unzip it and Install Eclipse IDE.
3. Launch Eclipse by clicking eclipse.exe
4. Click File=>New=>Project=>Web=>Dynamic Web Project
5. Click Next button
6. Put ajax in Project name and select 2.3 in Dynamic web module version
7. Click Finish button
8. Right-click on WebContent and click New=>JSP file and create hello.html
9. Replace following code with
<title>Simple Ajax Example</title>
<script language="Javascript">
function xmlhttpPost(strURL) {
var xmlHttpReq = false;
var self = this;
// Mozilla/Safari
if (window.XMLHttpRequest) {
self.xmlHttpReq = new XMLHttpRequest();
// IE
else if (window.ActiveXObject) {
self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}'POST', strURL, true);
self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
self.xmlHttpReq.onreadystatechange = function() {
if (self.xmlHttpReq.readyState == 4) {

function getquerystring() {
var form = document.forms['f1'];
var word = form.word.value;
qstr = 'w=' + escape(word); // NOTE: no '?' before querystring
return qstr;

function updatepage(str){
document.getElementById("result").innerHTML = str;
<form name="f1">
<p>Your name: <input name="word" type="text">
<input value="Go" type="button" onclick='JavaScript:xmlhttpPost("hello.jsp")'></p>
<div id="result"></div>

8. Right-click on WebContent and click New=>File file and create hello.jsp
9. Replace following code:

<%@ page language="java" contentType="application/x-www-form-urlencoded; charset=ISO-8859-1"
String w = request.getParameter("w");

String msg = "Hello "+w;

10. Click File=>Save
11. Right-click your ajax project.
12. Click Export=>war file
13. In Destination, put c:\ajax.war and click Finish button
Now you need publish your Hello World jsp on internet. I found a good JPS hosting company . They have free trial account. You can get your hosting space immediately, once you register on EATJ.
14. Once your EATJ account is activated, login to your EATJ account. Scroll down, you will find UPLOAD WAR FILES section. Click Browser button and go to c:\ and find your ajax.war and click Upload button.
15. Click Restart link. You will see something like http://<username>.<hostname>
16. Click this link. You will see Tomcat page.
17. Append hello/hello.jsp in your URL such as http://<username>.<hostname>
18. Put your name and click Go button

For this tutorial source code, you can download it at

Database tutorial: