Pages Navigation Menu

Coding is much easier than you think

Ajax implementation in Servlet without jQuery plugin

Ajax in Servlet without jQuery

 

AJAX is a technique for creating better, faster, and more interactive web applications. With AJAX, your JavaScript can communicate directly with the server, using the JavaScript XMLHttpRequest object. With this object, your JavaScript can transfer data with a web server, without reloading the page.
 
This post elaborates on how to implement Ajax in Servlet application.
 
** UPDATE: Servlet Complete tutorial now available here.
 

Folder Structure

 
AjaxWithOut Jquery
 

Jsp Page

 

<html>
<head>
<title>Ajax implementation in Servlet without Using jQuery</title>
<script type="text/javascript" src="js/ajax.js"></script>
</head>

<body>
	<h3>Ajax implementation in Servlet without jQuery</h3>
	<br />
	<div id="ajaxResponse" style="color: red; font-weight: bold"></div>
	<br /> Please Enter your Name :
	<input type="text" id="userName" onblur="doAjaxCall();" />
	<br />
</body>
</html>

 

JS File

 
File: ajax.js
In this file we will fire ajax to call java servlet.

//Get XMLHTTP Object
function getXMLHTTPObject() {
	var xmlhttpObject = null;
	try {
		// For Old Microsoft Browsers
		xmlhttpObject = new ActiveXObject("Msxml2.XMLHTTP");
	} catch (e) {
		try {
			// For Microsoft IE 6.0+
			xmlhttpObject = new ActiveXObject("Microsoft.XMLHTTP");
		} catch (e1) {
			// No Browser accepts the XMLHTTP Object then false
			xmlhttpObject = false;
		}
	}
	if (!xmlhttpObject && typeof XMLHttpRequest != 'undefined') {
		// For Mozilla, Opera Browsers
		xmlhttpObject = new XMLHttpRequest();
	}
	// Mandatory Statement returning the ajax object created
	return xmlhttpObject;
}

// Change the value of the outputText field
function setAjaxOutput() {
	document.getElementById('ajaxResponse').innerHTML = xmlhttpObject.responseText;
}

function handleServerResponse() {
	if (xmlhttpObject.readyState == 4) {
		if (xmlhttpObject.status == 200) {
			setAjaxOutput();
		} else {
			alert("Error during AJAX call. Please try again");
		}
	}
}

// Implement business logic
function doAjaxCall() {
	xmlhttpObject = getXMLHTTPObject();
	if (xmlhttpObject != null) {
		var URL = "AjaxAction?userName="
				+ document.getElementById('userName').value;
		xmlhttpObject.open("POST", URL, true);
		xmlhttpObject.send(null);
		xmlhttpObject.onreadystatechange = handleServerResponse;
	}
}

 

Recommended reading:

  • AJAX in Servlet & jsp using JQuery
  • jQuery Tutorial for Beginners
  •  

    Servlet

     
    Now let’s go on and write the servlet which handles this Ajax call

    package com.servlet;
    
    import java.io.IOException;
    import javax.servlet.ServletException;
    
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public class AjaxServlet extends HttpServlet {
    	private static final long serialVersionUID = 1L;
    
    	protected void doPost(HttpServletRequest request,
    			HttpServletResponse response) throws ServletException, IOException {
    
    		String userName = request.getParameter("userName");
    
    		if (userName.equals("")) {
    			userName = "User name cannot be empty";
    		} else {
    			userName = "Hello " + userName;
    		}
    		response.setContentType("text/plain");
    		response.getWriter().write(userName);
    	}
    }
    

    I hope the code above is self explanatory.
     

    Also read:

  • Dynamic dependent dropdown in Java web application using jQuery
  • Tab Style Login and Signup example using jQuery in Java web application
  •  

    Web.xml

     
    Make sure you have done servlet mapping in web.xml as shown below

    <web-app>
      <display-name>JqueryAjaxServlet</display-name>
      <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
      </welcome-file-list>
      <servlet>
        <servlet-name>AjaxAction</servlet-name>
        <servlet-class>com.servlet.AjaxServlet</servlet-class>
      </servlet>
      <servlet-mapping>
        <servlet-name>AjaxAction</servlet-name>
        <url-pattern>/AjaxAction/*</url-pattern>
      </servlet-mapping>
    </web-app>
    

     

    Demo

     
    Ajax WithOut Jquery Demo
     
    On running the application the above webpage is generated, in which enter a value in the textbox and click anywhere outside the textbox, then you will see a welcome message saying “Hello (userName)”.
     
    download
     

    About Mohaideen Jamil


    Am currently working as a Struts 2 Developer in a reputed IT Organisations. I can help you with teaching Core java and Struts 2. Follow me on Facebook or Google Plus. If you like my tutorials, consider making a donation to this charity, thanks.