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, get the response and use it in your JSP web pages.
Following are the steps to write AJAX code .
1. Create an XMLHttpRequest Object
All modern browsers (IE7+, Firefox, Chrome, Safari, and Opera) have a built-in XMLHttpRequest object.
Syntax for creating an XMLHttpRequest object:
xmlhttp=new XMLHttpRequest();
Old versions of Internet Explorer (IE5 and IE6) uses an ActiveX Object:
xmlhttp=new ActiveXObject(“Microsoft.XMLHTTP”);
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject(“Microsoft.XMLHTTP”);
}
2.Send a Request To a Server
To send a request to a server, we use the open() and send() methods of the XMLHttpRequest object
xmlhttp.open(“GET”,”ajax.do “,true);
xmlhttp.send();:
Method Description open(method,url,async) Specifies the type of request, the URL, and if the request should be handled asynchronously or not.
method: the type of request: GET or POST
url: the location of the file on the server
async: true (asynchronous) or false (synchronous) send(string) Sends the request off to the server.
3.The onreadystatechange event
When a request to a server is sent, we want to perform some actions based on the response.
The onreadystatechange event is triggered every time the readyState changes.
The readyState property holds the status of the XMLHttpRequest.
Three important properties of the XMLHttpRequest object:
Property | Description |
onreadystatechange | Stores a function (or the name of a function) to be called automatically each time the readyState property changes |
readyState | Holds the status of the XMLHttpRequest.0: request not initialized1: server connection established2: request received3: processing request4: request finished and response is ready |
status | 200: “OK”404: Page not found |
In the onreadystatechange event, we specify what will happen when the server response is ready to be processed.
When readyState is 4 and status is 200, the response is ready:
AJAX Example
Bellow example is : You have a dropdown with alphabets A,B and C , On selecting any of these, names starting with that alphabet will display in a List box.
<html> <head> <script language=”javascript”> function ajaxFunction(searchkey) { document.myForm.matches.options.length = 0; // This is for resetting the Names List xmlhttp = null if (window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest() } else (window.ActiveXObject) { xmlhttp = new ActiveXObject(“Microsoft.XMLHTTP”) } if(xmlhttp != null) { url = “AjaxServlet?key=”+searchkey; xmlhttp.open(“GET”,url,true); xmlhttp.send(null); xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { xmlDoc=xmlhttp.responseXML; // It could be either responseXML or responseText depends on the requirement. x=xmlDoc.getElementsByTagName(“NAMES”)[0]; for (i=0;i<x.childNodes.length;i++) { var name1= x.getElementsByTagName(“NAME”)[i]; var name=(name1.childNodes[0].nodeValue) ; document.myForm.matches.add(new Option(name,name,null)); } } } } // Closing if block else { alert(“Your browser does not support XMLHTTP.”) } } // Closing ajaxFunction </script> </head> <body> <form name=”myForm” method=get> Select Alphabet : <select name=”alpha” autocomplete=”off” onChange=”javascript:ajaxFunction(this.value)” > <option value=”A”>A</option> <option value=”B”>B</option> <option value=”C”>C</option> </select> <br><br> <select multiple=yes name=”matches”></select> </form> </body> </html>Servlet example to handle AJAX call
package com.j2eereference.ajax;
/* Author : Rakesh.B.K Date : 20.12.10 Version : 0.1 Name : AjaxServlet * Change History * * Date Added By Version Number Description * —- ———— ————– ———– * */ import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class AjaxServlet extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Sets the content type to xml specific response.setContentType(“text/xml”); response.setHeader(“pragma”,”no-cache”); response.setHeader(“Cache-Control”,”no-cache”); response.setHeader(“Cache-Control”,”no-store”); PrintWriter out = response.getWriter(); //Initializing PrintWriter String searchkey=request.getparameter(“key”); if(searchkey.equals(“A”)) buffer=“<NAMES><NAME>Ann</NAME><NAME>Ajay</NAME></NAMES>”; if(searchkey.equals(“B”)) buffer=“<NAMES><NAME>Bobit</NAME><NAME>Bharath</NAME></NAMES>”; if(searchkey.equals(“C”)) buffer=“<NAMES><NAME>Clinton</NAME><NAME>Clay</NAME></NAMES>”; out.write(buffer); out.flush(); out.close(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } }
Leave a Reply