Chapter 7 Use cookie

 

This chapter we will introduce how to use cookie. Cookies are used to get user agents (web browsers etc) to hold small amounts of state associated with a user's web browsing. Common applications for cookies include storing user preferences, automating low security user signon facilities, and helping collect data used for "shopping cart" style applications.

 

 

7.1 DCookie object

If we need to read and write cookies then must create DCookie object first. DCookie class represents a "Cookie", as used for session management with HTTP and HTTPS protocols.

Cookies are named, and have a single value. They may have optional attributes, including a comment presented to the user, path and domain qualifiers for which hosts see the cookie, a maximum age, and a version. Current web browsers often have bugs in how they treat those attributes, so interoperability can be improved by not relying on them heavily.

Cookies are assigned by servers, using fields added to HTTP response headers. In this API, cookies are saved one at a time into such HTTP response headers, using the response.addCookie method (refer to section 5.5). User agents are expected to support twenty cookies per host, of at least four kilobytes each; use of large numbers of cookies is discouraged.

Cookies are passed back to those servers using fields added to HTTP request headers. In this API, HTTP request fields are retrieved using the cookie module's request.getCookies method (refer to section 6.5). This returns all of the cookies found in the request. Several cookies with the same name can be returned; they have different path attributes, but those attributes will not be visible when using "old format" cookies.

 

Constructor: public DCookie(String iname, String ivalue)

Defines a cookie with an initial name/value pair. Names must not contain whitespace, comma, or semicolons and should only contain ASCII alphanumeric characters.

Names starting with a "$" character are reserved by RFC 2109.创

Parameters: iname - name of the cookie

        ivalue - value of the cookie

 

Methods:

1.       public String getName()

Returns: the name of the cookie. This name may not be changed after the cookie is created.

 

2.       public String getValue()

Returns: the value of the cookie.

 

3.       public void setValue(String newValue)

Sets the value of the cookie. BASE64 encoding is suggested for use with binary values.

Parameters: newValue – the value of need to reset

 

4.       public int getVersion()

Returns the version of the cookie. Version 1 complies with RFC 2109, version 0 indicates the original version, as specified by Netscape. Newly constructed cookies use version 0 by default, to maximize interoperability. Cookies provided by a user agent will identify the cookie version used by the browser.

 

5.       public void setVersion(int v)

Sets the version of the cookie protocol used when this cookie saves itself. Since the IETF standards are still being finalized, consider version 1 as experimental; do not use it (yet) on production sites. Default set 0.

 

6.       public void setComment(String purpose)

If a user agent (web browser) presents this cookie to a user, the cookie's purpose will be described using this comment. This is not supported by version zero cookies.

 

7.       public String getComment()

Returns: the comment describing the purpose of this cookie, or null if no such comment has been defined.

 

8.       public void setDomain(String pattern)

This cookie should be presented only to hosts satisfying this domain name pattern. Read RFC 2109 for specific details of the syntax. Briefly, a domain name name begins with a dot (".foo.com") and means that hosts in that DNS zone ("www.foo.com", but not "a.b.foo.com") should see the cookie. By default, cookies are only returned to the host which saved them.

 

9.       public String getDomain()

Returns: the domain of this cookie

 

10.   public void setMaxAge(int expiry)

Sets the maximum age of the cookie. The cookie will expire after that many seconds have passed. Negative values indicate the default behaviour: the cookie is not stored persistently, and will be deleted when the user agent (web browser) exits. A zero value causes the cookie to be deleted.

 

11.   public int getMaxAge()

Returns: the maximum specified age of the cookie. If none was specified, a negative value is returned, indicating the default behaviour described with setMaxAge.

 

12.   public void setPath(String uri)

This cookie should be presented only with requests beginning with this URL. Read RFC 2109 for a specification of the default behaviour. Basically, URLs in the same "directory" as the one which set the cookie, and in subdirectories, can all see the cookie unless a different path is set.

 

13.   public String getPath()

Returns: the prefix of all URLs for which this cookie is targetted

 

14.   public void setSecure(boolean flag)

Indicates to the user agent that the cookie should only be sent using a secure protocol (https). This should only be set when the cookie's originating server used a secure protocol to set the cookie's value.

 

15.   public boolean getSecure()

Returns: the value of the 'secure' flag

 

Notice: This implementation is not synchronized. If multiple threads access this DCookie concurrently, and at least one of the threads modifies the DCookie’s value (for example use “setValue”, “setMaxAge” method), it must be synchronized externally.

 

 

7.2 Example of use DCookie

For example, “writecookie.dqm” file can write cookie to client (web browsers etc), it’s source code:

1

2

3

4

5

6

7

<%@ page buffer="true"%>

<%

DCookie ck=new DCookie("username", "dunne");

ck.setMaxAge(30*60); // Set the maximum age of the cookie to 30 minutes

response.addCookie(ck); // write cookie to client

out.print("Write cookie ok.");

%>

From up source code 5st line you can see need use addCookie method to write cookie (refer to section 5.6). We enable buffer function in source code line 1, because write cookie need to enable buffer.

 

Next we introduce how to read cookie, “readcookie.dqm” can read all cookies from client, and it will display those cookie’s name. Source code:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

<%

DCookie cookies[]=request.getCookies(); // read all cookies

 

if(cookies.length == 0) {// if not found any cookie

  out.print("no any cookie");

}

else

{

  out.print(cookies.length + "<br>");

  for(int i = 0; i < cookies.length; i++) // loop read all cookies

  {

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

  }

}

%>

 

First we execute “writecookie.dqm”, after execute “readcookie.dqm”, then result:

2

DQMSESSIONID->fe7a9b1a-0b24-4a47-8bae-9e377ef16141

username->dunne

 

 From above results we can seen that found two cookies, but we only set a cookie so why can get two cookies? Actually another cookie was automatically created by session, about session please refer to chapter 8, so please don’t use “DQMSESSIONID” s cookie’s name, it was reserved by server.

If you knows cookie’s name, then can directly read cookie, “directreadcookie.dqm” file demonstrated how to directly read cookie, source code:

1

2

3

4

5

<%

String value =request.getCookieValue("username");

 

out.println("cookie's value: " + value);

%>

 

First we execute “writecookie.dqm”, after execute “directreadcookie.dqm”, then result:

cookie's value: dunne