Wednesday, November 30, 2011

Cookies

HTTP is a 'stateless' protocol - each new HTTP request is completely independent of the previous requests.

Most web applications need to be 'stateful',for example, web applications that need to identify clients through the course of a session (login->to->logout).

They use cookies.

Cookies are name/value pairs which applications can associate with a response. The browser returns these cookies in future requests (until the cookie 'expires' at a preset date/time).

Cookies are the backbone of 'stateful' web applications.

Java Servlet API provides a Cookie API for setting cookies.

Let us set a cookie in our application that gives a unique ID to each user.
Here is how HelloWorld.java looks like with cookie:


 package org.confucius;   

import java.io.IOException;
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;

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

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

response.getWriter().write("User ID = " + cookieValue);
}

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;
}
}


Let us understand what we did.

We maintain a static counter to track the next User ID (a simple integer)

We get the cookie from the request - if one is not found, we assign one.

Update your web.xml to direct the /home URL to HelloWorld Servlet:

 <web-app>   
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>org.confucius.HelloWorld</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/home</url-pattern>
</servlet-mapping>
</web-app>



If you build and deploy HelloWorld.war, then point your browser to:
http://localhost:8080/HelloWorld/home

You will first see that the User ID = null, becuase it starts off with no cookie.
If you refresh your browser, it will set the User ID to 1.
If you keep refreshing, it will continue to be 1.
If you close and restart your browser, the user ID will go to 2.

Note that since we did not explicitly set an expiry for the cookie, the cookie dies when the browser is closed.

No comments: