Friday, December 2, 2011

Stateful HelloWorld

Let us make HellowWorld 'stateful' - i.e. make it maintain some data ("state") between requests.

We will store the exact time a request is received. If the next request is received later than a certain threshold, we can potentially timeout the session. Many websites do this for security.

In this example, we will not actually timeout - we just want to demonstrate how to maintain 'state'.

We will maintain a simple Hashtable which maps the user ID (that we get from the cookie) to the time the request is received.

Here is what HelloWorld looks like now:
 package org.confucius;  

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HelloWorld extends HttpServlet {
private static int nextUserId = 0;
private static HashMap<String, Date> requestsTracker = new HashMap<String, Date>();

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String cookieValue = getCookieValue(request.getCookies(), "userId");

if (cookieValue == null) {
cookieValue = String.valueOf(nextUserId);
Cookie userCookie = new Cookie("userId", cookieValue);
response.addCookie(userCookie);
nextUserId++;
}

Date now = new Date();
response.getWriter().write(
"Your last request was received on: "
+ requestsTracker.get(cookieValue) + ", updating to: "
+ now);
requestsTracker.put(cookieValue, now);
}

private String getCookieValue(Cookie[] cookies, String cookieName) {
if (cookies == null)
return null;

for (int i = 0; i < cookies.length; i++) {
Cookie cookie = cookies[i];
if (cookieName.equals(cookie.getName()))
return (cookie.getValue());
}
return null;
}
}


Build HelloWorld.war, deploy it, then point your browser to:
http://localhost:8080/HelloWorld/home

Each time you refresh the browser, you will see the time that the last request was received.

No comments: