Ajax Servlet tutorial

Ajax Servlet tutorial

Ajax Servlet tutorial implementation: Ajax Servlet tutorial implementation: AJAX is a web development technique where group of interrelated object used on the client-side to build asynchronous web applications. Using Ajax, web applications could send and retrieve data from server asynchronously which is without interfering with display of processing and behavior of existing web page. Data could be retrieved using XMLHttpRequest object. AJAX (acronym for Asynchronous JavaScript and XML) as we see the name contains XML but the use of XML is not necessarily required (JSON could also be used instead) and the requests could be synchronous or asynchronous.

Ajax made of not a single technology but group of technologies. We can use styling in combination with HTML and CSS. DOM tree is accessed using JQuery or JavaScript to display the data dynamically and allow users to interact with the application. Main XMLHttpRequest and JavaScript provide method for exchanging data asynchronously or synchronously between browser and server and avoid the full page reloads.

Below demo will show you how to make ajax call to servlet which returns data in XML format. On the front end we will parse response XML data and show to the user.

Below are needed to run AJAX Servlet implementation application:

Please follow below steps:

  • Create dynamic web project in eclipse name: AJAXServletCallSample (Please use this link if you are not familiar how to create dynamic project in eclipse: Create Dynamic Web Project Eclipse)
  • Once you created dynamic web project in eclipse it should look similar to below

Ajax Servlet Tutorial

  • Create package name: com.javahorn.servlet inside src folder
  • Create class name: AjaxServlet inside package com.javahorn.servlet and copy below content in it:
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class AjaxServlet
 */
public class AjaxServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public AjaxServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		String firstName = request.getParameter("firstName");
		String lastName = request.getParameter("lastName");

		response.setContentType("text/xml");
		response.setHeader("Cache-Control", "no-cache");
		response.getWriter().write("<details>");
		response.getWriter().write("<firstName>"+firstName+"</firstName>");
		response.getWriter().write("<lastName>"+lastName+"</lastName>");
		response.getWriter().write("</details>");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}

 

  • Create index.jsp file inside WebContent folder and copy below content in it:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript">
	var xmlHttp;// global instance of XMLHttpRequest
	  function createXmlHttpRequest()
		{
			   if(window.ActiveXObject)
			   {
				xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
			  }

			else if(window.XMLHttpRequest)
			{
				xmlHttp=new XMLHttpRequest();
			 }

		}

	  function onChangeSubmitCallWebServiceAJAX()
		{
		  createXmlHttpRequest();
		  var firstName=document.getElementById("firstName").value;
		  var lastName=document.getElementById("lastName").value;
		  xmlHttp.open("GET","/AJAXServletCallSample/AjaxServlet?firstName="+firstName+"&lastName="+lastName,true)
		  xmlHttp.onreadystatechange=handleStateChange;
		  xmlHttp.send(null);

		}

		function handleStateChange()
		{
			if(xmlHttp.readyState==4)
			{
				if(xmlHttp.status==200)
					{		
						document.getElementById("firstName").value=
							xmlHttp.responseXML.getElementsByTagName("firstName")[0].childNodes[0].nodeValue;
						document.getElementById("lastName").value=
						xmlHttp.responseXML.getElementsByTagName("lastName")[0].childNodes[0].nodeValue;
					}
				else
				{
				   alert("Error loading pagen"+ xmlHttp.status +":"+xmlHttp.statusText);
				}
			}
		}

</script>
</head>
<body>

First Name: <input type="text" value="first" id="firstName"><br>
Last Name: <input type="text" value="Last" id="lastName"><br>
<input type="Submit" onclick="onChangeSubmitCallWebServiceAJAX();">

</body>
</html>

 

  • Please take note from below to find if call is asynchronous or synchronous
function onChangeSubmitCallWebServiceAJAX()
		{
		  createXmlHttpRequest();
		  var firstName=document.getElementById("firstName").value;
		  var lastName=document.getElementById("lastName").value;
		  xmlHttp.open("GET","/AJAXServletCallSample/AjaxServlet?firstName="
		  +firstName+"&lastName="+lastName,true)
		  xmlHttp.onreadystatechange=handleStateChange;
		  xmlHttp.send(null);

		}

Ajax Servlet Tutorial

 

  • Finally your project struct should look as below:

Ajax Servlet Tutorial

 

  • Refresh your project — Right click –> Run As –> Run on server as below:

Ajax Servlet Tutorial

 

Note: If you are not familiar with how to run dynamic web application Run on Server please follow below link to get familiar with it:

Ajax Servlet Tutorial

  • Enter First name and Last name click submit. Below are the AJAX call steps:
    • Once you click Submit Query button it will java script function : onChangeSubmitCallWebServiceAJAX()
    • On this function we are calling to servlet and pass all information
    • In AjaxServlet class we are pulling the request and sending response in XML format
    • Once response received by the servlet and once its in ready state we call handleStateChange java script function there we process response data from servlet and setting back in input fields.
  • Finally you see below screen after response comes back from the server:

Ajax Servlet Tutorial

  • That’s it. If you want please download project code below.

download Download Ajax Servlet tutorial

Note: If you download project code from below and import in your eclipse could see some exception, if you are using different version of JDK, ECLIPSE and Web server. Please use below link to sort out any issues:

 

Leave a Reply

Your email address will not be published. Required fields are marked *