Custom Search

Ajax Programming with JSP and Servlets

In Java World Servlets are popularly used for Model View Controller (MVC) Design Pattern. This article will guide you on writing AJAX based application for fetching data from the Servlet and showing it on JSP page.

JSP File Code:

<html>
<head>
<title>JSP and Servlet using AJAX</title>
<script type="text/javascript">
 
function getXMLObject()  //XML OBJECT
{
   var xmlHttp = false;
   try {
     xmlHttp = new ActiveXObject("Msxml2.XMLHTTP")  // For Old Microsoft Browsers
   }
   catch (e) {
     try {
       xmlHttp = new ActiveXObject("Microsoft.XMLHTTP")  // For Microsoft IE 6.0+
     }
     catch (e2) {
       xmlHttp = false   // No Browser accepts the XMLHTTP Object then false
     }
   }
   if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
     xmlHttp = new XMLHttpRequest();        //For Mozilla, Opera Browsers
   }
   return xmlHttp;  // Mandatory Statement returning the ajax object created
}
 
var xmlhttp = new getXMLObject();	//xmlhttp holds the ajax object
 
function ajaxFunction() {
  var getdate = new Date();  //Used to prevent caching during ajax call
  if(xmlhttp) { 
    xmlhttp.open("GET","gettime?" + getdate.getTime(),true); //gettime will be the servlet name
    xmlhttp.onreadystatechange  = handleServerResponse;
    xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xmlhttp.send(null);
  }
}
 
function handleServerResponse() {
   if (xmlhttp.readyState == 4) {
     if(xmlhttp.status == 200) {
       document.myForm.time.value=xmlhttp.responseText; //Update the HTML Form element 
     }
     else {
        alert("Error during AJAX call. Please try again");
     }
   }
}
</script>
<body>
<form name="myForm">
Server Time:<input type="text" name="time" />
<br />
<input type="button" onClick="javascript:ajaxFunction();" value="Click to display Server Time on Textbox"/>
<br />
</form>
</body>
</head>
</html>

Explanation for the AJAX Code

Here i have declared 3 JavaScript function:
getXMLObject() - Responsible for creating the AJAX Object depending on the browser.
ajaxFunction() - Responsible for calling servlet through AJAX call.
handleServerResponse() - Responsible for displaying the data retrieved from the server.




How the AJAX Code Works:

Servlet Code

import java.io.*;
 
import java.text.*;
 
import java.util.*;
 
import javax.servlet.*;
 
import javax.servlet.http.*;
 
public class gettime extends HttpServlet {
 
	public void init(ServletConfig config) throws ServletException {	
		super.init(config);
	}
 
	public void destroy() {
 
	}
 
	public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
		PrintWriter out = response.getWriter();
		Date df = new Date();
		out.println(df.getTime());
	}
 
	public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
		doPost(request,response);
	}
}

Explanation for the Servlet Code

Related Post

Did you enjoy this post? Why not leave a comment below and continue the conversation, or subscribe to my feed and get articles like this delivered automatically to your feed reader.

Comments

thanks
but i want some other codes of ajax with jsp and servlet. codes like auto fill after selection from list.

Leave a comment

(required)

(required)