Working With Cookies in JAVA

Describing Cookies

 
A cookie is a small information sent by a web server to a web client. Cookies are saved at the client-side for the given domain and path. The cookie file persists on the client machine and the client browser returns the cookies to the original. Cookies are small bits of textual information that a Web server sends to a browser and that the browser returns unchanged when visiting the same Web site or domain later. By having the server read information it sent the client previously, the site can provide visitors with a number of conveniences. Whenever the browser requests a resource, the cookie matching the domain and the path of the request URL is sent to the WEB Server. Cookies are transmitted to the server through HTTP headers in the request sent to the server.
The Servlet API provides a class named Cookie under the javax.servlet.http package. It provides us with a convenient way to create and read cookie data. to send data a servlet use addCookie() method of the httpServletResponse. to retrieve the cookie in a request returned by the browser, the Servlet uses the getCookies() method.
 

Creating Cookies

 
A cookie is created by calling the Cookie constructor, which takes two strings: the cookie name and the cookie value. Neither the name nor the value should contain whitespace or any of:
  
{[ ] ( ) = , " / ? @ : ;}
  
Cookie Attributes:  
  1. getComment/setComment
    Gets or sets a comment associated with this cookie.
  2. getDomain/setDomain
    Used to gets or sets the domain with which the cookie is associated.
  3. getMaxAge/setMaxAge
    Gets or sets how much time (in seconds) should elapse before the cookie expires. If you don't set this, the cookie will last only for the current session (i.e. until the user quits the browser), and will not be stored on disk.
  4. getName/setName
    Gets or sets the name of the cookie. The name and the value are the two pieces you virtually always care about.
  5. getPath/setPath
    Gets or sets the path to which this cookie applies. If you don't specify a path, the cookie is returned for all URLs in the same directory as the current page as well as all subdirectories.  
  6. getSecure/setSecure
    Gets or sets the boolean value indicating whether the cookie should only be sent over encrypted (i.e. SSL) connections.  
  7. getValue/setValue
    Gets or sets the value associated with the cookie. Again, the name and the value are the two parts of a cookie that you almost always care about, although in a few cases a name is used as a boolean flag, and its value is ignored (i.e the existence of the name means true). 
  8. getVersion/setVersion
    Used to set or get the version of the cookie, respectively. 
Advantages:
  • Reduced network traffic as compared to URL rewriting.
  • Used to maintain the data for a client.
  • Reduced the application logic complexity.
Disadvantages:
  • Cookies are not secured
  • These are HTTP specific thus it can be used for HTTP request only.
  • A client has the option to disable cookies.
Example: In this application, I describe how to add and retrieve cookies to maintain client data. This application has four files:
 
Index.jsp:
  1. <html>  
  2. <body bgcolor="skyblue">  
  3. <form action="AddCokieServlet.java"><pre>  
  4. Name:<input type="text" name="cname"/><br/>  
  5. Value:<input type="text" name="cvalue"/><br/>  
  6. <input type="submit" value="Add Cookie"/>  
  7. </pre> </form>   
  8. </body>  
  9. </html>  
AddCookieServlet.java: 
  1. package my;  
  2. import java.io.IOException;  
  3. import java.io.PrintWriter;  
  4. import javax.servlet.*;  
  5. import javax.servlet.http.*;  
  6. import javax.servlet.http.HttpServletRequest;  
  7. import javax.servlet.http.HttpServletResponse;  
  8.   
  9. public class AddCokieServlet extends HttpServlet   
  10. {  
  11. public void service(HttpServletRequest req, HttpServletResponse res)throws ServletException, IOException   
  12.     {  
  13.           String name=req.getParameter("cname");  
  14.           String value=req.getParameter("cvalue");  
  15.           Cookie c=new Cookie(name,value);  
  16.           res.addCookie(c);  
  17.           res.setContentType("text/html");  
  18.           PrintWriter out = res.getWriter();  
  19.           String output="<html><body>";  
  20.           output+="Cookie Added Successfully <br/>";  
  21.           output+="<a href='index.jsp'>Add one More <br/>";  
  22.           output+="<a href='viewcookies'>View Cookies <br/>";  
  23.           output+="</html></body>";  
  24.           out.println(output);  
  25.       }  
  26. }  
GetCookieServlet.java: 
  1. package my;  
  2. import java.io.IOException;  
  3. import java.io.PrintWriter;  
  4. import javax.servlet.*;  
  5. import javax.servlet.http.*;  
  6. import javax.servlet.http.HttpServletRequest;  
  7. import javax.servlet.http.HttpServletResponse;  
  8.   
  9. public class GetCokieServlet extends HttpServlet   
  10. {  
  11. public void service(HttpServletRequest req, HttpServletResponse res)throws ServletException, IOException   
  12.     {  
  13.         res.setContentType("text/html;charset=UTF-8");  
  14.         PrintWriter out = res.getWriter();  
  15.         out.println("<html><body><table border=1>");  
  16.         out.println("<tr><th>Name</th><th>Value</></tr>");  
  17.          Cookie[] c=req.getCookies();  
  18.         if(c!=null)  
  19.         {  
  20.           for(int i=0;i<c.length;i++)  
  21.           {  
  22.            out.println("<tr><td>"+c[i].getName()+"</td>");  
  23.            out.println("<tr><td>"+c[i].getValue()+"</td>");  
  24.            }  
  25.          }  
  26.        out.println("</table><br/><br/>");  
  27.        out.println("<a href='index.jsp'>Add One More</a><br/>");  
  28.        out.println("</body></html>");  
  29.      }  
  30. }  
web.xml: 
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">  
  3. <servlet>  
  4. <servlet-name>AddCokieServlet</servlet-name>  
  5. <servlet-class>my.AddCokieServlet</servlet-class>  
  6. <load-on-startup>2</load-on-startup>  
  7. </servlet>  
  8. <servlet>  
  9. <servlet-name>GetCookieServlet</servlet-name>  
  10. <servlet-class>my.GetCookieServlet</servlet-class>  
  11. <load-on-startup>3</load-on-startup>  
  12. </servlet>  
  13. <servlet-mapping>  
  14. <servlet-name>AddCokieServlet</servlet-name>  
  15. <url-pattern>/AddCokieServlet</url-pattern>  
  16. </servlet-mapping>  
  17. <servlet-mapping>  
  18. <servlet-name>GetCookieServlet</servlet-name>  
  19. <url-pattern>/viewcookies</url-pattern>  
  20. </servlet-mapping>  
  21. <welcome-file-list>  
  22. <welcome-file>index.jsp</welcome-file>  
  23. </welcome-file-list>  
  24. </web-app>  
After that, we run this application on Server the outputs of this application is given below:
  
Index.jsp:
 
index.gif
 
AddCookieServlet.java:
 
add.gif
 
GetCookieServlet.java:  
 
get.gif