JaiswalTraining

Get the online training



Corejava Servlet Jsp  Php  Hibernate  Ajax Web Service   Ejb2.1 Ejb3.0 Struts Struts2  JPA Spring Ibatis   JSF    JSF2.0  CoreJavaDesignPattern    Jquery  Flex J2EE-Design-Patterns  Jboss7  Maven  Contact Me                                                                                                                                                                        
            IGNOU SMU PTU Project                                           Training                                                                                                                              
              

Contact Us  0091- 9210721663         jaiswaltraining@gmail.com




Corejava
Servlet
Jsp
Php
Hibernate
Ajax
Web Service
Ejb2.1
Ejb3.0
Struts  
Struts2
JPA
Spring
Ibatis
JSF
JSF2.0
CoreJavaDesignPattern
Jquery
Flex
J2EE-Design-Patterns
Jboss7
Maven







Handling Cookies

  • Understanding the benefits and drawbacks of cookies

  • Sending outgoing cookies

  • Receiving incoming cookies

  • Tracking repeat visitors

  • Specifying cookie attributes

  • Differentiating between session cookies and persistent cookies

  • Simplifying cookie usage with utility classes

  • Modifying cookie values

  • Remembering user preferences

Cookies are small bits of textual information that a Web server sends to a browser and that the browser returns unchanged when later visiting the same Web site or domain Most browsers avoid caching documents associated with cookies, so the site can return different content each time.

  • Syntax
public Cookie(java.lang.String name,java.lang.String value)

name - Sring specifying the name of the cookie
valueString specifying the value of the cookie

By default, cookies are created according to the Netscape cookie
specification. The version can be changed with the setVersion()
method
Advantages of Cookies 
  • Identifying a user during an e-commerce session.
  • Avoiding username and password.
  • Customizing a site.
  • Focusing advertising
Points to Remember
  • A browser accept 20 cookies per client and 300 cookies total.
  • The size of each cookie limited to 4KB 

Sending cookies to Client
  •  Creating cookie object
  •  Setting Maximum Age
  •  Placing Cookie into HTTP response headers. 
Creating Cookie object

You can create cookie by Cookie constructor, which takes two string Cookie name and cookie value.

 Neither the name nor value should contain white spaces or any of these symbols.

 [],(),=“/ ? @ : ;

 Cookie c1=new Cookie(“userid”,”a123”);

 Setting Maximum age

C1.setMaxAge(60*60*24*7) //one week

 Adding cookies

response.addCookie(c1);

 

 Reading and Specifying Cookie Attributes

   Before adding the cookie to the outgoing headers, you can look up or set attributes of the cookie. Here's a summary:

     getComment/setComment

       Gets/sets a comment associated with this cookie.

   getDomain/setDomain

   Gets/sets the domain to which cookie applies. Normally, cookies are returned only to the exact hostname that sent them. You can use this method to instruct the browser to return them to other hosts within the same domain. Note that the domain should start with a dot (e.g. .prenhall.com), and must contain two dots for non-country domains like .com, .edu, and .gov, and three dots for country domains like .co.uk and .edu.es.


 getMaxAge/setMaxAge

public void setMaxAge(int expiry)

    Gets/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.

A positive value indicates that the cookie will expire after that many seconds have passed. Note that the value is the maximum age when the cookie will expire, not the cookie's current age.

A negative value means that the cookie is not stored persistently and will be deleted when the Web browser exits. A zero value causes the cookie to be deleted.

public int getMaxAge()

eturns the maximum age of the cookie, specified in seconds,By default, -1 indicating the cookie will persist
until browser shutdown

getName/setName

   Gets/sets the name of the cookie. The name and the value are the two pieces you virtually always care about. Since the getCookies method of HttpServletRequest returns an array of Cookie objects, it is common to loop down this array until you have a particular name, then check the value with getValue

public void setValue(java.lang.String newValue)

public java.lang.String getValue()
 getPath/setPath

          Gets/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. This method can be used to specify something more general. For example, someCookie.setPath("/") specifies that all pages on the server should receive the cookie. Note that the path specified must include the current directory.

public void setPath(java.lang.String uri)
public java.lang.String getPath()

getSecure/setSecure

          Gets/sets the boolean value indicating whether the cookie should only be sent over encrypted (i.e. SSL) connections.

 

 getValue/setValue

    Gets/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).

public void setValue(java.lang.String newValue)

public java.lang.String getValue()

 getVersion/setVersion

          Gets/sets the cookie protocol version this cookie complies with. Version 0, the default, adheres to the original Netscape specification 

public void setVersion(int v)
public int getVersion()
 Getting the Value of a Cookie with a Specified Name

String color=CookieUtilities.getCookieValue(request,”color”,”black”);

String font=CookieUtilities.getCookieValue(request,”font”,”Arial”);

 

package myservlet;
 
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
public class CookieDemo extends HttpServlet{
 
  public void doGet(HttpServletRequest request, HttpServletResponse response)
  throws IOException{
 
    response.setContentType("text/html");
    PrintWriter pw = response.getWriter();
 
    Cookie cookie = new Cookie("url","myservlet dot com");
    cookie.setMaxAge(60*60)//1 hour
    response.addCookie(cookie);
 
    pw.println("Cookies created");
  }
}

    
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" 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>
        <servlet-name>ServletName</servlet-name>
        <servlet-class>myservlet.CookieDemo</servlet-class>
    </servlet>
 
    <servlet-mapping>
        <servlet-name>ServletName</servlet-name>
        <url-pattern>/Demo</url-pattern>
    </servlet-mapping>
 
<servlet>
        <servlet-name>PrintCookieServlet</servlet-name>
        <servlet-class>myservlet.ServletDemoCookie</servlet-class>
    </servlet>
 
    <servlet-mapping>
        <servlet-name>PrintCookieServlet</servlet-name>
        <url-pattern>/printCookie</url-pattern>
    </servlet-mapping>
 
</web-app>

  Output

 

 


    

package mycookie;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Cookie1 extends HttpServlet {
  private static final long serialVersionUID = 1L;

  protected void doGet(HttpServletRequest request,
      HttpServletResponse responsethrows ServletException, IOException {
    Cookie c1 = new Cookie("emp1""e001");
    Cookie c2 = new Cookie("emp2""e002");
    Cookie c3 = new Cookie("emp3""e003");

    response.addCookie(c1);
    response.addCookie(c2);
    response.addCookie(c3);

    response.getWriter().print("cookie added");
  }

}

 
Download code

Output



In browser  Tools---->Options---------->Privacy-------->remove individual cookies




Cookie2.java
package mycookie;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Cookie2 extends HttpServlet {
  private static final long serialVersionUID = 1L;

  protected void doGet(HttpServletRequest request,
      HttpServletResponse responsethrows
ServletException, IOException {

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    Cookie cookie[] = request.getCookies();
    out.print("<br><br>Name-----Value<br>");
    for (int i = 0; i < cookie.length; i++) {

      out.print("<br>" + cookie[i].getName() "-----"
          + cookie[i].getValue());

    }

  }

}
Download code


 output: Getting values Manually



 
CustomerCookie.java

package mycookie;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CustomerCookie extends HttpServlet {
  private static final long serialVersionUID = 1L;

  protected void doGet(HttpServletRequest request,
      HttpServletResponse responsethrows ServletException, IOException {

    Cookie c[] new Cookie[3];
    String cname[] "cust1""cust2""cust3" };
    String cval[] "c101""c102""c103" };
    int age[] 10, -10};

    for (int i = 0; i < c.length; i++) {
      c[inew Cookie(cname[i], cval[i]);
      c[i].setMaxAge(age[i]);
      response.addCookie(c[i]);
    }
    response.getWriter().print("Three customer cookie  added");
  }
}
Download code
Output


Three  cookies added first.....!




Third cookie whose Maxage set to 0,  destroy  instantly..



And cookie whose Maxage was set to 10 destroy after 10 sec.
Finally the cookie whose maxage set to negative will remain there..!