Pages

Saturday, June 30, 2012

Session Tracking using Cookies

Cookies are piece of information sent by any web application to a web browser. and this information is further used to track the client state(data).
In my last post i wrote about session tracking with the help of hidden form fields but i also mentioned there that the hidden form fields are not effective in most of the situations.
So cookies are our next hope and cookies are nice indeed as they sound, I am going to discuss how.

Whenever a client or end user sends a request to a web application by supplying some information in the form of request body or through URL.
The web appliction does :
  • Grab all the information from the request body or URL(Depends on the request method either get or post).
  • Create cookies for each of these information elements.(!! creating cookies is far easy you will see very soon)
  • Now that the information is encapsulated in the cookies the web application sends these cookies back to the requesting browser as a response.  
 Now the browser plays its role :
  • The duty of browser is to store the cookies received from the web-application in some private location with Domain name and path of web-application from where the cookies arrived.
  • Now when the cookies are stored,whenever next request is made from the same browser to the same domain the browser automatically embeds all the cookies matching that particular domain to the request body.
  Note: Every Browser keep its cookies separately. ex. Internet Explorer don't share its cookies with Mozilla or any other,and same is the case with any other browser.

pictorial representation of cookie transfer mechanism

As you can observe above the mechanism of cookies is very simple.This was the general concept of how the cookies work.This concept remain same, doesn't matter on whether you use JAVA, PHP or .net.

But i am totally java oriented person so Lets relate the concept of cookies with the java technology.

Cookie : is a class in java come with javax.servlet.http package with one and only two argument constructor.
Cookie(String ,"value"); 
second argument to the constructor can be of any type i.e String,int,double,float,boolean etc.
>> Creating a cookie:
You can't create a cookie object without providing these two arguments i.e name and value.
Syntax for creating a Cookie object is :

Cookie cuki=new Cookie("uasername","wilson");

in the above line of java code "cuki" is a complete cookie with name "username" and value "wilson".

Every cookie in the world is created in the same way as shown above.

>> Now the second minor challenge is to pass the cookie to the browser back.

we do it like this:

response.addCookie("reference to cookie object");

After adding the cookie to the response the role of Server side application is almost over.
>> Now the browser will store the cookie in a predefined fashion
that is:
whenever the browser receives a cookie it first checks whether there is prior cookie from the same domain with same name.

case1: if a cookie is already present there with same name and domain
          browser just replace it with the new one.
case2: if the cookie is new to the browser then it stores the cookie normally.

>> After storing the cookie,the prime duty of browser is to attach all the associated cookies for a domain to any of request made for that domain.

>> And the web application utilizes these cookies to identify client states.


This was all theoretical view of working of cookies.
now its time for a real and working example which will show you the complete picture:

//index.html the starting page.

<html>
<head>
<%@page language="java"%>
<title>cookies tutorial</title>
</head>
<body bgcolor="gray">
<form name="login" action="Storecookies">
UserName:<input type="text" name="uname"/><br/>
Password: <input type="password" name="pass"/><br/>
<input type="submit" value="login"/>
</form>
</body>
</html>


// this is the source of Storecookies servlet.

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
public class Storecookies extends HttpServlet
{
    public Storecookies(){
    }
  
    public void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException
    {
        Enumeration paras=req.getParameterNames();
        PrintWriter pw=resp.getWriter();
        String rem=req.getParameter("remember")
      while(paras.hasMoreElements())                                                                             
            {                                                                                                                     
                String pname=(String) paras.nextElement();                                                  
                String pvalue=req.getParameter(pname);                                                      
                Cookie c=new Cookie(pname,pvalue);                                                           
                c.setPath("/*");                                                                                            
                resp.addCookie(c);                                                                                       
            }                                                                                                                     
            pw.write("<b>cookies are stored successfully</b>");                                            
            pw.write("<a href='Showcookies'>show me the cookies</a>");                               
    }                                                                                                                             
}                                                                                                                                 


// Source of Showcookies Servlet.


import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class Showcookies extends HttpServlet
{
   
    public void doGet(HttpServletRequest req,HttpServletResponse resp)throws ServletException,IOException
    {
       
        Cookie c[]=req.getCookies();
       
        PrintWriter pw=resp.getWriter();
        pw.write("<html><body bgcolor='gray'>");
        for(int i=0;i<c.length;i++)
        {
            String name=c[i].getName();
            String value=c[i].getValue();
       
            pw.println(name+" -> "+value+"<br/>");
        }
            pw.write("</body></html>");

    }
    public void doPost(HttpServletRequest req,HttpServletResponse resp)throws ServletException,IOException
    {
        doGet(req,resp);
    }

}

// web.xml file with Servlet mappings

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee   http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
 <servlet>
  <description>just testing servlets</description>
  <servlet-name>Storecookies</servlet-name>
  <servlet-class>Storecookies</servlet-class>
 </servlet>
 <servlet-mapping>
  <servlet-name>Storecookies</servlet-name>
  <url-pattern>/Storecookies</url-pattern>
 </servlet-mapping>
 <servlet>
  <servlet-name>Showcookies</servlet-name>
  <servlet-class>Showcookies</servlet-class>
 </servlet>
 <servlet-mapping>
  <servlet-name>Showcookies</servlet-name>
  <url-pattern>/Showcookies</url-pattern>
 </servlet-mapping>
 <welcome-file-list>
  <welcome-file>index.jsp</welcome-file>
 </welcome-file-list>
</web-app>


This was a Simple application imlementing cookies to store client data.You can easily Deploy this simple and ready made application and checkout the outcome.

Now i want to add some methods which are provided by Cookie class for providing advance control over cookies.

>>What is Age for a cookie?

Its the time period for which the browsers keep a cookie and after expiring of that time period they delete the cookie.
We can set Maximum age for any cookie using the below method

setMaxAge(time in seconds);

Default MaxAge for any cookie is -1 which instructs browser to keep the cookie till the browser is running,once the browser is closed cookie is lost.

>> We can set Domain name for a cookie explicitly if we like to do so.otherwise its automatically set by the web containers. 

setDomain("Domain name");

>> We can decide the paths for which the browser should send the cookie within a applicatin,like if you want a cookie to be sent only for the login page in your web applicatin.you can do it like this

setPath("/login.jsp");

>> Cookies are of two types secured and insecure
Secured cookies use https(hypertext secure socket layer) protocol.But cookies are insecure by default.

setSecure("boolean"); //provide true as argument to make a cookie secure.

>> To get value of a cookie object we use the below method on the cookie object:

getValue();

>> To get name of a cookie :
getName();

>> If you want to know MaxAge of a cookie use 
getMaxAge();



 --------------------------------------------------------------------------------------


 support by providing your valuable feedback !!

No comments:

Post a Comment