Cookies are the small textual information which allocate the memory at client side by remembering client data across the multiple requests during a session. The web resource programs of web application create cookies at server side but these cookies come to client side along with the response and allocate memory at client side. Cookies of client side go back to their web application along with the request given by clients (browser windows to web resource programs).
There are two types of cookies:
1. In memory cookies/per session cookies: This allocates memory in browser window having “-1″as the expiry time (no expiry time). These cookies will be destroyed automatically once browser window is closed.
2. Persistent cookies: These cookies allocate memory in the files of client machine hard disk having positive number as expiry time. These cookies will not be destroyed when browser window is closed but they will be destroyed when their expiry time is reached.
The cookie that is created without expiry time is called in memory cookie. The cookie that is created with expiry time is called persistent cookie. To work with cookies we must deal with predefined HttpServlet class-based servlet programs.
Every cookie contains name and value as String information. At client-side or browser window we can see multiple cookies belonging to different domains or web applications. Every cookie remembers the web application name or domain name for which it is created.
Cookies of one web application that are there at client side will go to their web application along with the request. The browser window then sends the request back to that application.
With respect to the diagram:
(1) The form page1 Tax.html gives request1 to Srv1 of CookieAppl web application.
(2) Srv1 program reads form1 data, creates two in memory cookies having that form1 data.
(3) Srv1 generates response to browser window adding the cookies and having dynamic form page. These cookies allocate memory on browser window as in memory cookies.
(4) The dynamic form2 page generates request to Srv2 of Cookie application so that two cookies of CookieAppl go to Srv2 progra-n along with the request.
(5) Srv2 reads form2 data normally but reads request1 data from the cookies of request2.This indicates that Srv2 is able to use the request1 data while processing form2 request/request (which is nothing but session tracking).
(6) Srv2 writes both form1 and form2 data to database table.
(7) Srv2 program generates dynamic web page having form1 and form2 data.
The web resource programs of web application send cookies to client machine along with the response as ‘set-cookie’ response header values. The browser window sends the cookies back to web application along with the request giv2n to web resource programs as cookies request header value.
Cookie-api: (Working with javax.servlet.http.Cookie)
Cookie ckl= new Cookie ("ap" ,"hyd"); / / ap->cookie name &hyd-->cookie value res.addCookie (ck1) ; / / adding cookie to response Cookie ck1= new Cookie ("mh", "mumbai"); //ap-->cookie name &hyd-->cookie value Ck2.setMaxAge (1800); / / setting expiry time res.addCookie (ck2); / / adding cookie to response
Here, ck2 cookie is persistent cookie having 1800 seconds as expiry time
To know max age of cookie (expiry time)
int time=ckl. getMaxAge (); / /gives -1 (in memory cookie) int time=ck2.getMaxAge(); //gives 1800
To know cookie value
ck1.setValue ("new hyd"); ck2.setValue("navimumbai");
To know domain name/web application name of the cookie
String d1=ck1.getDomain(); String d2=ck2.getDomain();
To set comment to cookie
ckl.setComment("holds ap's capital city"); ck2.setComment(holds mh's capital city");
To get comment of cookie
String c1=ck1.getComment(); String c2=ck2.getComment();
To read cookie values
String ck [ ] =req.getCookies ( ) //reads all the cookies from the current http request if (ck! =null) { for(int i=0;i<ck.length;i++) { pw.println("cookie name"+ck[i].getName()); pw.println("cookie name"+ck[i].getValue()); }}
To delete cookies:
Cookies cannot be deleted with codes. In memory cookies will be destroyed automatically once their browser window is closed. Persistent cookies will be destroyed if their expiry time is reached.
In Windows XP while working with Internet Explorer the persistent cookies of web application will be stored in the files created in c:\document and settings \ administrator\cookies folder and notation of the file is:
<windows user>@<web application name>[<cookies count>] .txt
Writing HTML code in servlet program with attribute value of HTML tags
pw.println("<table border=1 align=center>");
If we try to modify the content of a file where persistent cookies are stored then persistent cookies including that file will be destroyed. Internet Explorer allocates\the memory for in memory cookies on browser window, whereas the memory for persistent cookies will be allocated as files on the client hard disk.
In Netscape Navigator both in memory and persistent cookies have expiry time.
Note: Netscape Navigator also internally uses client machine hard disk files for storing persistent cookies.
Every cookie remembers the domain name or web application name to which it belongs. Cookies belonging to Yahoo.com website will go to Yahoo.com website only when browser window or client gives request back to that Yahoo.com website.
In email web sites, the “Remember me on this computer” option in the login page stores the given login details (username, password) as persistent cookies on client machine hard disk. Thus, using persistent cookies, we can remember client data during and after session.
Develop the above application
Step 1: Prepare the deployment directory structure of web application
Step 2: Develop the source code of above servlet program or web application.
Tax.html
<head> <style> .label { font-family:"Palatino Linotype", "Book Antiqua", Palatino, serif; font-size:14px; color:#0e0e0e; } .border { border:solid 2px #0448e0; margin-top:70px; } .text { font-family:"MS Serif", "New York", serif; font-size:16px; color:#070200; } </style> <title>tax</title> </head> <body> <form action="Taxservlet1" method="get"> <table cellpadding="2px" cellspacing="1px" bgcolor="#F4F5F7" width="400px" class="border" align="center"> <tr> <td colspan="2" bgcolor="#0066FF"></td> </tr> <tr> <td colspan="2" class="label"></td> </tr> <tr> <td align="center" colspan="2"> <span class="text">Enter Info</span> </td> </tr> <tr> <td colspan="2" class="label"></td> </tr> <tr> <td class="label" align="right" width="40%"><b>Name:</b></td> <td align="left" width="60%"><input type="text" name="name" maxlength="20"/></td> </tr> <tr> <td class="label" align="right"><b>FatherName:</b></td> <td align="left"><input type="text" name="fname" maxlength="20" /></td> </tr> <tr> <td class="label" align="right"></td> <td align="left"><input type="submit" value="Click" /></td> </tr> <tr> <td colspan="2" class="label"></td> </tr> </table> </form> </body> </html>
FirstSrv1
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class Taxservlet1 extends HttpServlet { public void doGet (HttpServletRequest rq, HttpServletResponse rs) throws ServletException, IOException { PrintWriter disp; rs.setContentType ("text/html"); disp=rs.getWriter(); String name = rq.getParameter("name"); String fname = rq.getParameter("fname"); Cookie c1 = new Cookie ("Name" ,name); Cookie c2 = new Cookie ("F_name" , fname) ; rs.addCookie(c1); rs.addCookie(c2) ; disp.println("<center><b>") ; disp.println ("<form action='Taxservlet2' method=get>"); disp.println("<center><br>Income for this year <input type='text' name='Income'><BR>"); disp.println(" <center><br>Tax<input type='text' name=tax>"); disp.println ("<br><br><input type='submit' value ='submit' >") ; disp.println("</form></center>") ; disp.close( ) ; } }
SecondSrv2
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class Taxservlet2 extends HttpServlet { public void doGet (HttpServletRequest rq,HttpServletResponse rs) throws ServletException, IOException { PrintWriter disp; rs.setContentType("text/html"); disp=rs.getWriter(); String income=rq.getParameter("Income"); String tax = rq.getParameter ("tax") ; disp.println ("<center><b>") ; disp.println ("<center><br>Income:"+income) ; disp.println("<center><br>Tax :"+tax); Cookie[ ] c=rq.getCookies(); if(c!=null) { for(int i=0;i<c.length;i++) { disp.println(c[i].getName() +" ..... "+c [i] . getValue ( )) ; } } disp.println("</center>"); disp.close(); } }
Web.xml
<servlet> <servlet-name>Taxservlet1</servlet-name> <servlet-class>Taxservlet1</servlet-class> </servlet> <servlet-mapping> <servlet-name>Taxservlet1</servlet-name> <url-pattern>/Taxservlet1</url-pattern> </servlet-mapping> <servlet> <servlet-name>Taxservlet2</servlet-name> <servlet-class>Taxservlet2</servlet-class> </servlet> <servlet-mapping> <servlet-name>Taxservlet2</servlet-name> <url-pattern>/Taxservlet2</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>second</servlet-name> <url-pattern>/second</url-pattern> </servlet-mapping> </web-app>
Step 3: Compile the source files of all servlet programs.
Step 4: Configure all the four servlet programs in web.xml file having four different url patterns.
Step 5: Start the server (Tomcat).
Step 6: Deploy the web application and Copy CookieApp folder to Tomcat_home \ webapps folder.
Step 7: Test the web application.
Open browser window type this URL: https://ecomputernotes.com:2020/CookieApp/Tax.html
In this web application, we will be using separate form pages either for personal details and technical details. But we are going to need data of both of them to print in the dynamic web page.
In the first form page, we need to enter the personal details of the client and submit the same. On submission, request is generated for the first servlet program “Srv1”. In Srv1, we will read the data entered by the client and store them in String objects. In order to access these data throughout the session and across the form pages, we need to store them in cookies. While constructing the cookies we will give any name to it but while assigning the values to it, we will pass the corresponding String object.
Similar operation is done to enter the details for income and tax. Here, we will read the data stored in the cookies and print all the details of first as well as second form page.
Advantages
• Cookies allocate the memory at client side so, they do not burden the server.
• All server side technologies, web servers and application servers support cookies.
• Persistent cookies can remember client data during session and after session with expiry time.
Disadvantages
• Cookies cannot store Java objects as values. They can store only string.
• Cookies data can be viewed through browser settings or through the files in file System so they do not provide data secrecy.
• Cookies can be deleted explicitly through browser settings but it may cause failure of session tracking.
• While creating each dynamic form page we have to add the previous form page’s data as hidden box value. This increases burden on the programmers.
• Cookies can be blocked/ restricted from coming to browser window. This causes session tracking.
To delete cookies
1. Internet Explorer
Tools internet options delete cookies
2. Netscape
Tools cookies manager remove all cookies
To block cookies
1. Internet Explorer
Tools internet options privacy use slider
2. Netscape
Tools cookies manager block cookies from this site