Search This Blog

Friday 18 March 2016

Reverse AJAX - what and how ?

I had only heard about the concept of reverse AJAX before. So when I started looking at servlets async behavior I was tempted to check out this concept.
AJAX is basically an asynchronous technique of communication used in browsers to allow sections of page to communicate with the server without a complete reload. Here the point to note is that all requests are of the type Client requesting some data from the server. What if the server wants to send some data to the client ? For instance server wants the client to know that a particular event of the client's interest has occurred. How does the server inform the client ?
This is where reverse AJAX comes into the picture. Reverse Ajax allows the server to push information to the client.  The point to remember is there is no way for the server to initiate communication with the client. The server has to use AJAX techniques to achieve reverse AJAX.
The simplest way to achieve reverse AJAX is polling. Consider that you have a web application where you need to ensure that the session times out after exactly 5 minutes of inactivity.
In the absence of reverse AJAX you would check every client request to see if this has occured after 5 minutes of inactivity. In that case redirect user to logout page.
Problem with this approach is that the user's page stays open and visible to others until somebody tries to perform an activity. With polling, this problem can be avoided.
Consider the below index.jsp page
<html>
<head>
    <script>
  var pollAndCheck = function () {
   document.getElementById("sessionActve").innerHTML="Checking..." ;
    if (window.XMLHttpRequest) {
      // code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
    } else {  // code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function() {
      if (xmlhttp.readyState==4 && xmlhttp.status==200) {
        document.getElementById("sessionActve").innerHTML=xmlhttp.responseText;
      }
    }
    xmlhttp.open("POST","isActive",true);
    xmlhttp.send();
  };
  
  //check every 2.5 minutes
  window.setTimeout(pollAndCheck, 2.5*60*1000);
  
</script>
</head>



<%
session = request.getSession(false);
if (session != null) {
  session.invalidate();
}
session = request.getSession(true);
System.out.println("Session has been activated at " + session.getCreationTime());
%>

<body>
    
    <h3>Hello, This is a sample page</h3>
    <br/><br/><br/>
    Is your session active ?? <div id="sessionActve"></div>  

</body>
</html>
The page is a simple welcome page.
  1. On server side it initializes the user session. 
  2. It also includes a client side code that checks if user session is active. 
  3. The code executes every 2.5 minutes. 
Next is the servlet that is responsible for providing this information to the browser.
@SuppressWarnings("serial")
public class SessionCheckServlet extends HttpServlet {

  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    System.out.println("Request received for a check at " + new Date());
    HttpSession session = req.getSession(false);
    PrintWriter writer = resp.getWriter();
    if (session == null) {
      writer.write("false");
    } else {
      writer.write("true");
    }
    writer.flush();
  }
}
I configured the session timeout and the servlet in my web.xml:
<session-config>
      <!-- This is in minutes -->
      <session-timeout>2</session-timeout>
   </session-config>

   <servlet>
      <servlet-name>SessionCheckServlet</servlet-name>
      <servlet-class>com.app.web.SessionCheckServlet</servlet-class>
   </servlet>
   <servlet-mapping>
      <servlet-name>SessionCheckServlet</servlet-name>
      <url-pattern>/isActive</url-pattern>
   </servlet-mapping>

   <welcome-file-list>
      <welcome-file>index.jsp</welcome-file>
   </welcome-file-list>
</web-app>
Now when I run the code:
Thus using polling the client can be informed by the server when the session timeouts. Important thing is how often does the client query ?
If the client queries too often, chances of detecting the even change sooner is higher. But the difference is the amount of requests that occur. Too many requests from several clients - this solution would struggle to scale.
There are two other techniques too which I want to try out. I shall look at them in coming posts.

1 comment: