Wednesday, December 31, 2014

Session tracking with persistent cookies in Java

Cookies are used to store certain client information in client side. It is created by server, sent to browser, and browser manages cookies to identify itself to the server when re-connected.
  • Cookie is a bit of information sent by a web server to a browser
  • Browser stores cookie on client machine and later sends back to server each time it access page on that server
  • Generally used to identify client, list client's preferences and used for session tracking
  • Some browsers don't support or accept cookies
  • javax.servlet.http Cookie class is used for working with cookies.
  • Cookies can be created with Cookie() constructor with initial name and value
    • public Cookie(String name, String value)
  • Servlet can send a cookie to the client by passing a Cookie object to addCookie() method of HttpServletResponse
    • public void HttpServletResponse.addCookie(Cookie cookie)
  • Cookies are sent using HTTP headers so they should be added to response before any content is sent to the client
  • Multiple cookies can be added to a response
  • Browsers generally accept 20 cookies per site and 300 cookies per client and may limit cookie size to 4KB

Example: Set cookie with initial id field

//set cookie with initial id field
Cookie cookie=new Cookie("id","123"); 
 
//add cookie to the response object
response.addCookie(cookie); 
 
//retrieve cookie from the client
Cookie[] cookies = request.getCookies(); 
 
if(cookies!=null){
  for(int i=0;i<cookies.length;i++){
    String name=cookies[i].getName();
    String value=cookies[i].getValue();
}}

Some methods of cookies used for session tracking

  • Maximum expiry age in seconds; negative value specifies default and zero value specifies, cookie is deleted when browser exists
    • public void Cookie.setMaxAge(int expiry)
    • public int getMaxAge()
    • public void Cookie.setVersion(int v)
  • Return domain of the cookie, null if not defined
    • public String getDomain()
  • Set domain attribute to define which hosts the cookie should be presented to by the client ( eg .example.com)
    • public void Cookie.setDomain(String pattern)
  • Indicate the user agent that this cookie should only be sent via secure channel like HTTPS
    • public void Cookie.setPath(String uri)
  • Assign new value to cookie
    • public void Cookie.setValue(String newValue)
  • Return the value of cookie
    • public String getValue()

Example session tracking using persistent cookie. Implementing shopping cart in Java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class ShoppingCartViewerCookie extends HttpServlet {
  public void doGet(HttpServletRequest request, HttpServletResponse response) 
   throws servletException, IOException{
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    //get the current sessionid if exists by searching the received cookies
    String sessionid=null;
    Cookie[] cookies = request.getCookies();

    if(cookies!=null){
      for(int i=0;i<cookies.length;i++){
        if(cookies[i].getName().equals("sessionid")){
          sessionid=cookies[i].getValue();
          break();
        }
      }
    }
 
    //set session id if it was not found and send it to client with response
    if(sessionid==null){
      sessionid=generateSessionId();
      Cookie c = new Cookie("sessionid",sessionid);
      response.addCookie(c); 
 
    //display information about shopping cart after setting sessionid
    out.println("<html><head><title>Shopping cart</title></head><body>");

    //cart items are associated with session id
    String items = getItemsFromCart(sessionid);
    out.println("<h1>You have following items in your shopping cart</h1>");

    if(items==null){
      out.println("No items");
    } else {
      out.println("<ul>");
      for(int i=0; i<items.length;i++)
        out.println("<li>"+ items[i] + "</li>");
      out.println("</ul>");
    }

    //Ask if client want more item or check out
    out.println("<form action=\"/servlet/ShoppingCart\" method="POST">");
    out.println("<input type=submit value=\"Add more items to cart\">");
    out.println("<input type=submit value=\"Check out\">");
    out.println("</form>");
}}

No comments:

Post a Comment