Java Reference
In-Depth Information
Now that you've seen how to view cookies manually, let's look at how you create them and read
them using code. You start by looking at each of the parts that make up a cookie string.
the Cookie string
When you are creating a cookie, you can set six parts: name , value , expires , path , domain ,
and  secure , although the latter four of these are optional. You'll now look at each of these
in turn.
name and value
The first part of the cookie string consists of the name and value of the cookie. The name is used so
that you can reference the cookie later, and the value is the information part of the cookie.
This name/value part of the cookie string is compulsory; it sort of defeats the point of the cookie
if you don't store a name or value, because storing information is what cookies are all about. You
should make sure that this part comes first in the cookie string.
The value for the cookie is a primitive string, although the string can hold number characters if it is
numerical data that you want to store. If you are storing text, certain characters, such as semicolons,
cannot be used inside the value, unless you use a special encoding, which you'll see later. In the case
of semicolons, this is because they are used to separate the different parts of the cookie within the
cookie string.
In the following line of code, you set a cookie with the name UserName and the value Paul :
document.cookie = "UserName=Paul;";
This cookie has a very limited lifespan , which is the length of time the information will continue
to exist. If you don't set an expiration date, a cookie will expire when the user closes the browser.
The next time the user opens the browser the cookie will be gone. This is fine if you just want to
store information for the life of a user session , which is a single visit by the user to your website.
However, if you want to ensure that your cookie is available for longer, you must set its expiration
date, which you look at next.
expires
If you want a cookie to exist for longer than just a single user session, you need to set an expiration
date using the second part of the cookie string, expires , as follows:
document.cookie = "UserName=Paul;expires=Tue, 28 Dec 2020 00:00:00 GMT; ";
The cookie set by the previous line of code will remain available for future use right up until
December 28, 2020.
Note The format of the expiration date is very important. It should be the
same format the cookie is given by the toUTCString() method.
 
Search WWH ::




Custom Search