Saturday, April 27, 2013

2.1.1 Cookies and Servlets

As Http is a stateless protocol, it doesn't remember client information between request intervals. Each request is new to him. But in some kind of applications like shopping card apps, website tracking, visitor profile generation it is necessary that the server does remember information about the client.

Cookie is small amount of data captured by the server and stored in the client end. Each time the client visits a website, server checks if there is any cookie present in the clients end and then responses accordingly.

  • There are 6 parameters that can be passed to a cookie:
  • The name of the ccookie
  • The value of the cookie
  • The expiration date of the cookie
  • The path the cookie is valid for
  • The domain for a secure connection to exist to use the cookie
Again, there are two types of cookies:
  • Permanent/Persistent Cookies-Cookies are not destroyed after closing the browser.
  • Session/ Transient Cookies-in this case, cookies are destroyed after the browser is closed.

Ok, let's move on to create and retrieve some cookie on our own. We shall create a cookie that accepts user input and remembers it for a specified time. When the client visits the page within this time, the information is shown to him. 

First, let's set the cookie.

@WebServlet(name = "SetCookieServlet", urlPatterns = "/setCookie")
public class SetCookieServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        Cookie songCookie = new Cookie("songCookie", "Welcome to the Hotel California!");
        songCookie.setMaxAge(10);              //in seconds
        response.addCookie(songCookie);       //important! This line actually transfers the cookie to the browser

    }
}

Now, in another servlet, we shall retrieve the cookie value.

@WebServlet(name = "GetCookieServlet", urlPatterns = "/getCookie")
public class GetCookieServlet extends HttpServlet {
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setContentType("text/html;charset=UTF-8");

        PrintWriter out = response.getWriter();

        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("songCookie")) {
                    out.println(cookie.getValue());
                }
            }
        }

    }
}


Hit the url /setCookie once. This will create the cookie which will be alive for 10 seconds. By this time, hit the url /getCookie. You should see the title of one of my most favorite songs.
 

No comments:

Post a Comment