Thursday, 27 September 2012

simple XMLHttpRequest example with jsps


1)The bellow given is the jsp page where i am using xmlhttprequest to retrive the header information and a text file in the application asynchronously
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc(url)//the parameter url for our resource
{
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();//creating a new object for ajax
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");//creating a new object for ajax
  }
xmlhttp.onreadystatechange=function()//Stores a function (or the name of a function) to be called //automatically each time the readyState property changes
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)//if status is succes and request is processed
    {
    document.getElementById('p1').innerHTML=xmlhttp.getAllResponseHeaders();//getting all response data
alert(xmlhttp.getResponseHeader('Content-Type'));//getting specific response data
alert(xmlhttp.responseText);
    }
  }
xmlhttp.open("GET",url,true);//it is making a get request with our url asynchronously
xmlhttp.send();
}
</script>
</head>
<body>

<p id="p1">The getAllResponseHeaders() //function returns the header information of a resource, like length, server-type, content-type, last-modified, etc.</p>
<button onclick="loadXMLDoc('xmlhttp_info.txt')">Get header information</button>//here is our onclick function
</body>
</html>







2)xmlhttp_info.txt this file should be in the context path of the application
3)in web.xml welcome file lis tyou should mention the jsp name

<?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_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>groupsPrac</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>deskto.jsp</welcome-file>//mention name of your jsp
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>

No comments:

Post a Comment

Custom single threaded java server

 package com.diffengine.csv; import java.io.*; import java.net.*; import java.util.Date; public class Server { public static void main(Str...