Pages

Wednesday 10 September 2014

Simple AJAX example in JSP/Servlet

AJAX (Asynchronous JavaScript and XML) is a group of interrelated Web development techniques used on the client-side to create asynchronous Web applications. With Ajax, Web applications can send data to, and retrieve data from, a server asynchronously (in the background) without interfering with the display and behavior of the existing page. Data can be retrieved using the XMLHttpRequest object.

AJAX comes to your rescue when there is only a small amount of data that needs to be updated on a page already loaded and rest of data remains the same. In such case you need not reload the whole page, rather you would go with the reload of specific data.

Here is the example of how Ajax can be used in JSP and Servlets:

index.jsp

<%@ 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>My Page</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 getEmployeeDetails() {

if(xmlhttp) {  
var empId = document.getElementById("empId").value;
xmlhttp.open("POST","EmployeeDetails?"+"empId="+empId,true);
  xmlhttp.onreadystatechange  = responseHandler;
    xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xmlhttp.send(null);
  }
}

function responseHandler() {

if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
document.frm.txtarea.value=xmlhttp.responseText;      
      }else {
        alert("Error occured while AJAX call..... Please try again.....");
      }
    }
}
</script>

</head>

<body>
<form name="frm">
<table width="100%">
<tr style="width: 100%;">
<td style="padding-left: 40px;  padding-top: 10px; padding-bottom: 10px">Employee Id ::   
<input type="text" id="empId" style="width: 150px">
   
<a style="padding-right: 40px;">
<input style="background-color:#092A6B;color:#FFFFFF;width: 150px ;font-size: 15; cursor: pointer;" type="button" value="Retrieve Details" onClick="getEmployeeDetails();">
</a>
</td>
</tr>
<tr style="width: 100%;">
<td style="padding-left: 30px; padding-bottom: 10px">
<textarea name="txtarea" style="width: 670px; height: 100px;"></textarea>
</td>
</tr>
</table>
</form>
</body>
</html>



EmployeeDetails.java

package com.shakeel;

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;

/**

 * Servlet implementation class EmployeeDetails
 */
public class EmployeeDetails extends HttpServlet {
private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public EmployeeDetails() {
        super();
        // TODO Auto-generated constructor stub
    }

/**

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

/**

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

PrintWriter out = response.getWriter();
response.setContentType("text/xml");
String empId = request.getParameter("empId");
String result = "";

if(empId.equalsIgnoreCase("E100")){
result = " Name: Shaan \n Address: Bangalore \n Role: Programmer";
}else if(empId.equalsIgnoreCase("E101")){
result = " Name: Shakeel \n Address: San Francisco \n Role: Lead";
}else{
result = " Employee Id does't exist.... Please try some other Employee Id...";
}

out.println(result);
}


}


web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>AjaxExample</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>

  <servlet>

    <description></description>
    <display-name>EmployeeDetails</display-name>
    <servlet-name>EmployeeDetails</servlet-name>
    <servlet-class>com.shakeel.EmployeeDetails</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>EmployeeDetails</servlet-name>
    <url-pattern>/EmployeeDetails</url-pattern>
  </servlet-mapping>

</web-app>



Output




I hope this example would have helped you in understanding of how exactly AJAX calls are made and the result is retrieved.





10 comments:

  1. Nice blog post on Ajax servlet. The blog which you have shared is really great. thanks for taking time to provide us this useful information. Keep on blogging like this unique content

    SAP ABAP Training in Chennai

    ReplyDelete
  2. Another great articles and very interesting to read,thanks for sharing that wonderful useful information,given programming coding was very excellent and easily observe all provided information.
    digital marketing training in chennai

    ReplyDelete
  3. Wow! great work.For this example really very excellent,i can easily understand all given information.Given HTML was amazing,i really very impressed after visit the post.
    ios training in chennai

    ReplyDelete
  4. Thanks for sharing these niche piece of coding to our knowledge. Here, I had a solution for my inconclusive problems & it’s really helps me a lot keep updates…
    Regards,
    JAVA Training|JAVA Training in Chennai|Java Courses in Chennai

    ReplyDelete
  5. Hi Admin, I went through your article and it’s totally awesome. You can consider including RSS feed for easy content sharing, So that you can drive huge traffic to your blog.
    Regards,
    Hadoop Training Chennai|Big Data Training|Hadoop Training in Chennai

    ReplyDelete
  6. Excellent article,it was helpful to us to learn more and useful to teach others.This like valuable information is very interesting to read.


    Salesforce Training in Chennai Adyar

    ReplyDelete