Tuesday, February 19, 2013

AJAX with Java Servlet


AJAX with Java Servlet


To Understand this exp you should have basic knowledge of Servlet, Javascript and HTML.

About the example:
1. we have a simple user.html form with two fields username and time.
2. as soon as user inputs its name the time field will be populated with server’s current time using ajax.
 

Screenshots


When application is deployed :


After entering name:


As soon as you click on ‘Time’ field it will get automatically populated



Folder Structure:

Files :


1. 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>AjaxTest</display-name>
  <welcome-file-list>
    <welcome-file>user.html</welcome-file>
  </welcome-file-list>
 
  <servlet>
  <servlet-name>Hello</servlet-name>
  <servlet-class>in.ibm.TimeTest</servlet-class>
  </servlet>
  <servlet-mapping>
  <servlet-name>Hello</servlet-name>
  <url-pattern>*.url</url-pattern>
  </servlet-mapping>
 
</web-app>

2. TimeTest.java

package in.ibm;
import java.util.Calendar;

import javax.servlet.http.*;

public class TimeTest extends HttpServlet {
              public void doPost(HttpServletRequest req, HttpServletResponse res) throws java.io.IOException {
                           Calendar c=Calendar.getInstance();
                            res.setContentType("text/html");
                            res.getWriter().write(c.getTime().getHours()+":" + c.getTime().getMinutes() + ":" + c.getTime().getSeconds());
                          }
                         
                          public void doGet(HttpServletRequest req, HttpServletResponse res)
                              throws java.io.IOException {
                            doPost(req, res);
                          }
}


User.html
<html>
<body>

<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
function ajaxFunction(){
      var ajaxRequest;  // The variable that makes Ajax possible!
     
      try{
            // Opera 8.0+, Firefox, Safari
            ajaxRequest = new XMLHttpRequest();
      } catch (e){
            // Internet Explorer Browsers
            try{
                  ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                  try{
                        ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
                  } catch (e){
                        // Something went wrong
                        alert("Your browser broke!");
                        return false;
                  }
            }
      }
      // Create a function that will receive data sent from the server
      ajaxRequest.onreadystatechange = function(){
            if(ajaxRequest.readyState == 4){
                  document.myForm.time.value = ajaxRequest.responseText;
            }
      }
      ajaxRequest.open("POST","hi.url",true);
      ajaxRequest.send(null);
}

//-->
</script>



<form name='myForm'>
Name: <input type='text' onChange="ajaxFunction();" name='username' /> <br />
Time: <input type='text' name='time' />
</form>
</body>
</html>


Explaination:



1. The soul of ajax is XMLHttpRequest Object, so always, to use Ajax in your application try to get XMLHttpRequest object first.

2. XMLHttpRequest has various properties like readyState, responseText, responseXML, status, statusText.

3. readyState is a place where response from server will be stored, it can have 5 values

0 – Object is uninitialized
1 – Request is loading
2 – Request is fully loaded
3 – Request is waiting for user interaction
4 – Request is complete

4.  responseText and responseXML will contain the response from the Server.
5. status and statusText contains the values

200: "OK"
404: Page not found

Hence if readyState value is 4 and status is 200, we can say that we have got a response from server and we can go ahead and use the response.

6. Once request is ready, we have to open a connection kind of thing with server or we can say before sending created request using ajax we have to get connection. we have one method called

                   XMLHttpRequest.open(method,url,async)

7. Send the request using method

                   XMLHttpRequest.send();
8. XMLHttpRequest have one eventListener name onreadystatechange which will listen any change in readyState value, so we can this listener to listen the changes in state and assign some javascript function to it to make the required changes in page as per the state change



No comments: