XMLHttpRequest Object example project using Java


Friends the following udemy course created by me;

      Click here to attend Spring Framework 4.x and certification course with a discount

Spring Framework and Core Spring Certification Udemy course with discount
Spring Framework and Core Spring Certification Udemy course with a discount coupon

I have coded a small J2EE web project for using XMLHttpRequest object on a J2EE web application. By using this object, users can call a method on the server without refreshing the whole HTML page. Refreshing only the small parts of pages are enough if you use XMLHttpRequest object. First of all, I need an application server running on my computer. So , you should have one also on your computer. (I am using APACHE Tomcat for this example)

Here is the web.xml file;

<xml version="1.0" encoding="UTF-8"?>
 <xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"
 <display-name>XMLHttpRequestExample</display-name>
 <welcome-file-list>
 <welcome-file>index.html</welcome-file>
 <welcome-file>index.htm</welcome-file>
 <welcome-file>index.jsp</welcome-file>
 <welcome-file>default.html</welcome-file>
 <welcome-file>default.htm</welcome-file>
 <welcome-file>default.jsp</welcome-file>
 </welcome-file-list>
 <servlet>
 <description></description>
 <display-name>MyServlet</display-name>
 <servlet-name>MyServlet</servlet-name>
 <servlet-class>com.servlets.MyServlet</servlet-class>
 </servlet>
 <servlet-mapping>
 <servlet-name>MyServlet</servlet-name>
 <url-pattern>/MyServlet</url-pattern>
 </servlet-mapping>
 </web-app>

Server class: Servlet‘s content is;

 package com.servlets;

 import java.io.IOException;
 import javax.servlet.ServletException;
 import javax.servlet.http.HttpServlet;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 import javax.xml.parsers.DocumentBuilder;
 import javax.xml.parsers.DocumentBuilderFactory;
 import javax.xml.parsers.ParserConfigurationException;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 import com.sun.org.apache.xml.internal.serialize.XMLSerializer;

public class MyServlet extends HttpServlet {

 private static int counter = 0;
 private static final long serialVersionUID = 1L;

 public MyServlet() {
 super();
 }

 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 doPost(request, response);
 }

 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 System.out.println("XMLHttpRequest has executed.................");

 Document DOCUMENT = null; // XML Document

 try {

 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
 DocumentBuilder documentBuilder = factory.newDocumentBuilder();
 DOCUMENT = documentBuilder.newDocument(); // assign empty XML Document
 Element MESSAGES = DOCUMENT.createElement("MESSAGES");
 Element MESSAGE = DOCUMENT.createElement("MESSAGE");
 Element CONTENT = DOCUMENT.createElement("CONTENT");

 CONTENT.setTextContent("XMLHttpRequest has completed, It works.... (Server Talks).... counters ---> " + (++counter));
 DOCUMENT.appendChild(MESSAGES);
 MESSAGES.appendChild(MESSAGE);
 MESSAGE.appendChild(CONTENT);

 //XML's structure
 //<MESSAGES>
 // <MESSAGE>
 // write your content here by calling setTextContent method
 // </MESSAGE>
 //</MESSAGES>

response.setHeader("Cache-Control", "no-cache");
 //set the content type
 response.setContentType("text/xml");

XMLSerializer xmlserializer = new XMLSerializer(response.getOutputStream(), null);
 xmlserializer.serialize(DOCUMENT); //Serialize the document as XML for Response

} catch (ParserConfigurationException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }
 }
 }

And, index.jsp;

 <%--
 Document : index.jsp
 Created on : May 5, 2011, 10:59:51 AM
 Author : tunatöre
 --%>
 <%@page contentType="text/html" pageEncoding="UTF-8"%>
 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=UTF-8">
 <title>Tuna TÖRE</title>
 </head>
 <body>
<h1>Testing XMLHttpRequest Object</h1>
<body>
 <div id="data"><!--XML Data will be here--></div> <br/>
 <button>Test XMLHttpRequest Object</button>
 </body>
 </body>
 </html>
 <script type="text/javascript">
 var httpRequest;
 /**
 *
 * This function creates XMLHttpRequest request for communicating with the server (servlet method)
 * and calls processRequest method after it gets the data from SERVER
 */
 function getMessageContent()
 {
 //change this URL with your SERVER's URL and port number
 var url = 'http://localhost:8080/XMLHttpRequestExample/MyServlet'; // sending request - URL mapping is inside WEB.xml file

if (window.ActiveXObject)
 {
 httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
 }
 else if (window.XMLHttpRequest)
 {
 httpRequest = new XMLHttpRequest();
 }
 httpRequest.open("GET", url, true);
 httpRequest.onreadystatechange = function() { processRequest(); } ; //calling processRequest method
 httpRequest.send(null);
 }

/**
 * This functions is a call back method
 * After the call is completed and if the readyState is 4
 * and if the HTTP request is successfull (the status is 200)
 * It will update data section (DIV element on index.jsp page)
 */

function processRequest()
 {
 if (httpRequest.readyState == 4) //call is completed true
 {
 if(httpRequest.status == 200) //http request is successfull
 {
 //get the XML data send by the servlet
 var XMLdata = httpRequest.responseXML.getElementsByTagName("CONTENT")[0];
 //Update the HTML --> filling data div content without refreshing full page
 updateHTML(XMLdata);
 }
 else
 {
 alert("Error ---> \n"+ httpRequest.status + " : " + httpRequest.statusText);
 }
 }
 }
 /**
 * This function parses the XML and updates the
 * HTML DOM by creating a new text node is not present
 * or replacing the existing text node.
 */
 function updateHTML(XMLdata)
 {
 //Create the Text Node with the XML data
 var MESSAGEBODY = document.createTextNode(XMLdata.childNodes[0].nodeValue);
 //Get the reference of the DIV by passing the ID
 var data = document.getElementById("data");
 //Checking if the node exists
 if(data.childNodes[0])//If yes then replace it with the new one
 {
 data.replaceChild(MESSAGEBODY, data.childNodes[0]);
 }
 else
 {
 //If not then new child appends
 data.appendChild(MESSAGEBODY);
 }
 }
 </script>

Download XMLHttpRequestObject project’s source code

Advertisements