Getting Started with AJAX using Java : Tutorial

We learnt how AJAX works in previous articles; now we want to explore some techniques for using AJAX with Java technologies such as Java Server Pages (JSP), Java Server Faces (JSF) and others.

The most common way of using AJAX with Java technologies is to use JavaScript. You need to have AJAX functions, such as, creating an XMLHttpRequest object for your browser, then using the object requests for a JSP page or Servlet (in general, for an URL), get the response and use it in your JSP web pages. For this, what I usually do is, I create a JavaScript file with all these functions and include this .js file in my web pages using a <script> tag, and use the functions mentioned there. This is a very common technique of using AJAX with JSP, and this is almost the same for PHP. The following example will clear the concept more.

Problem: We need to get the server date time from a JSP page using AJAX.

Solution: First we will create a JSP web page that will output server data time like the one below.

<%=new java.util.Date()%>

Save the above line of code as index.jsp. The output will be as follows.

Now create   the necessary JavaScript functions, like the one I typically use.

function createRequestObject(){

var req;

if(window.XMLHttpRequest){
//For Firefox, Safari, Opera
req = new XMLHttpRequest();
}
else if(window.ActiveXObject){
//For IE 5+
req = new ActiveXObject(“Microsoft.XMLHTTP”);
}
else{
//Error for an old browser
alert(‘Your browser is not IE 5 or higher, or Firefox or Safari or Opera’);
}

return req;
}

//Make the XMLHttpRequest Object
var http = createRequestObject();

function sendRequest(method, url){
if(method == ‘get’ || method == ‘GET’){
http.open(method,url);
http.onreadystatechange = handleResponse;
http.send(null);
}
}

function handleResponse(){
if(http.readyState == 4 && http.status == 200){
var response = http.responseText;
if(response){
document.getElementById(“ajax_res”).innerHTML = response;
}
}     
}

I usually save the above script as ajax.js. Add this JavaScript in your invoker JSP page (the page that will invoke the index.jsp to get the server date time) using AJAX.

The invoker JSP, caller.jsp –

<%@page contentType=”text/html”%>
<%@page pageEncoding=”UTF-8″%>

<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”
“http://www.w3.org/TR/html4/loose.dtd”>

<html>
<head>
<script src=”ajax.js”></script>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
<title>JSP Page using AJAX</title>
</head>
<body>

        <a onclick=”sendRequest(‘GET’,'index.jsp’)” href=”#”>Server Date Time:</a>
<div id=”ajax_res”>Server Date Time will replace this text.</div>
</body>
</html>

This caller.jsp has a <div> element with the id=’ajax_res’. When I the user clicked the link ‘Server Date Time:’ as shown below, the JavaScript function sendRequest from ajax.js would be called to get the data from ‘index.jsp’ using HTTP GET method. The output of caller.jsp before clicking the link is

The output of caller.jsp after invoking the index.jsp using AJAX is

This way you can use AJAX with JSP for retrieving information from Database or from any file kept in the server, or can send the user information to server and get the response.

//break//

There is also an OpenSource project called AjaxTags. This AJAX Tag Library is a set of JSP tags that simplify the use of AJAX technology in Java Server Pages. This tag library offers following tags for common AJAX functionality.

  • Autocomplete: retrieves a list of values that matches the string entered in a text form field to a data store, just plain old autocomplete!
  • Callout: displays a callout or popup balloon, anchored to an HTML element with an onclick event
  • Select/dropdown: based on a selection within a dropdown field, a second select field will be populated, important for narrowing down the selections, like after selecting a country from a list another list shows only the states of the selected country
  • Toggle: toggles a form field between true and false and at the same time switches an image between two sources
  • Update field: updates one or more form field values based on response to text entered in another field, this is very cool for huge forms with several text and select fields
  • Portlet: portlet-style capability from a AJAX-enabled JSP tag
  • Tab Panel: enable an AJAX-based set of property pages.

This tag library relieves J2EE developers to write the necessary JavaScript to implement an AJAX-capable web form.

This implementation is a combination of Java classes and JavaScript source files. The Java code should be OS independent as there are no client side components. However, the Java is dependent on JDK 1.4+ and requires a Servlet container (like Tomcat) to run. The JavaScript should run in at least Firefox 1.0+ and Internet Explorer 5.0+.
To use AjaxTags tag library, first download it from http://ajaxtags.sourceforge.net/ and then copy the ajaxtags.jar into your WEB-INF/lib directory. Modify the web.xml for adding this tag library. Then add the dependency JavaScripts in your JSP pages. To learn more about this AjaxTags please visit the project homepage at http://ajaxtags.sourceforge.net/index.html.
There is another way of using AJAX with Java Server Faces user interface designs using Ajax4jsf. You can also use that. But the coolest AJAX tag library is jMaki. I’ll show you how to create a cool and nice with feature rich web page with jMaki and Netbeans 5.5 IDE in the next section.
According to the jMaki project team – jMaki is an Ajax framework that provides a lightweight model for creating JavaScript centric Ajax-enabled web applications using Java, PHP, and Phobos. To use jMaki with Netbeans IDE, first download the Netbeans module from https://ajax.dev.java.net/jmaki-plugin.html and install the module. Installation procedure is described nicely in this link.
After installing jMaki module you can create your web 2.0 applications with just some drags and drops. Some examples are here.
First, run the Netbeans IDE. Create a new project from File menu. Select web application. Select jMaki Ajax Framework. It will ask you to choose the CSS layout, select Standard one. It will create the banners, a side bar, home page link, sitemap link etc.

Here, you can see the JSP code at the left and the Palette at the right. There are a lots of jMaki widgets at the palette. jMaki has widgets for Flickr, Google, Yahoo and others. Using Flickr widgets, you can create captcha, word art, and search for images very easily. Let’s create an image search using jMaki Flickr widget. Just drag the widget from palette and drop in your JSP page. Now save the project, build and run. A browser will be opened as below.

Enter some va
lue in the edit box and click Search. It will get the images from Flickr using AJAX.

The JSP file looks like –
<%@ taglib prefix=”a” uri=”http://jmaki/v1.0/jsp” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>

<html>
<head>
<link rel=”stylesheet” href=”jmaki-standard.css” type=”text/css”></link>
<title>Page Title</title>
<meta http-equiv=”Content-Type” content=”text/html; charset=iso-8859-1″ />
</head>
<body>
<div class=”outerBorder”>

<div class=”header”>
<div class=”banner”>Application Name</div>

<div class=”subheader”>

<div>
<a href=”mailto:feedback@youraddress”>Feedback</a> |
<a href=”#”>Site Map</a> |
<a href=”#”>Home</a>
</div>

</div> <!– sub-header –>
</div> <!– header –>

            <div class=”main”>
<div class=”leftSidebar”>

Sidebar Content Here

</div> <!– leftSidebar –>

                <div class=”content” style=”height:400px”>

<a:widget name=”flickr.search”
args=”{
topic:’flickrSearch’,
columns:3,
count:9
}”
service=”/xhp”/>

</div> <!– content –>

</div> <!– main –>
</div> <!– outerborder –>
</body>
</html>

//break//

Now let’s try another example. Pick the clock widget from the palette and drop it in your JSP code. Your code should look like this.

<div class=”content” style=”height:400px”>                   
<a:widget name=”dojo.clock”  />                   

</div> <!– content –>

You can change the outlook of this widget also. To do this click within the code of the widget and then click jMaki button from Netbeans IDE as shown here.

Change the clockType value to Gray. The changed JSP would be like –

<div class=”content” style=”height:400px”>                   
<a:widget name=”dojo.clock” args=”{clockType:’gray’}”/>
</div>

Save the changes and refresh the browser. The output would be –

Here is a nice Yahoo slide bar for you.

<a:widget name=”yahoo.slider” />

Just add the above tag or drag it from palette. The output would be a nice simple slide bar.

Now add a Tabbed View widget from the palette in your code. The JSP code would be:

<div class=”content” style=”height:400px”>               
<a:widget name=”yahoo.tabbedview”
value=”{tabs:[
{label:'My Tab', content: 'Some Content'},
{label:'My Tab 2', content: 'Tab 2 Content'}
]
}” />

</div> <!– content –>

You can change the labels from ‘My Tab’ to anything you need. You can also have as many tabs as required. The above code will create two tabs with labels and contents as described in the above code segment. Here is the output of this.

Isn’t jMaki cool?! There are lots of other cool widgets for you. Explore all the widgets, you will love jMaki definitely. You can also add Google Search or Yahoo Search by simply just dragging and dropping. Also you can add Google Maps very easily in your web pages. You can have menus, calendars, trees, editor, editable table and lots of other cool widgets in your web application very easily.

There is good news for PHP developers. That is they can also use jMaki with PHP. I tried to describe different ways and techniques here in this article to use AJAX with JSP. You choose which one better fits your need. Now, go try out these solutions and learn AJAX.

Kick It on DotNetKicks.com    Shout it
Twitter Digg Delicious Stumbleupon Technorati Facebook Email

Comments are closed.