Cookies

 

Microsoft Corporation
October 2003

Applies to:
    Microsoft® ASP.NET
    Java Server Pages (JSP)

Summary: Learn how to work with cookies in both JSP and ASP.NET. (7 printed pages)

Contents

Introduction
Cookies in JSP
Cookies Run Through the JLCA
Cookies in ASP.NET
Cookie Attributes In ASP.NET
Summary

Introduction

If you've worked with any kind of Web application, chances are you've had to build and read cookies. Cookies are small text files that are stored by a client's Web browser. Each cookie consists of a name-value pair and several configuration attributes. Cookies have many different purposes. Some of these include storing user preferences for a Web site, remembering a user's login and password so that she does not have to log in every time she visits a site, or for keeping track of user actions in a Web application (for example, a cookie might be used to keep track of what parts of an application a user has visited so that quick-links can be provided back to those locations).

Assuming you have a Web browser installed on your machine, you can find the location where your browser stores its cookies and open a cookie in a text editor. For example, Internet Explorer usually stores its cookies in the directory C:\Documents and Settings\UserName\Cookies. Listing 1 shows what we would see if we opened a cookie called craig wills@google[1].txt from this directory (assuming Craig Wills is the current user).

Listing 1. An example of a cookie

PREF
ID=40dbd37914242a34:TM=1013725751:LM=1013725751:S=P4MUPnk7Wbs
google.com/
1536
2618878336
32111634
48239568
29472167

This cookie is built and distributed by Google.com. The first line is the name of the cookie, and the second line contains the cookie's value (which, in this case, is actually a set of name-value pairs separated by colons; this is Google.com-specific). The rest of the lines are attributes set by Google.com.

Cookies in JSP

In JSP, cookies are encapsulated as javax.servlet.http.Cookie objects. A Cookie object may be added to an HttpResponse object using HttpResponse.addCookie(). To extract a cookie from an HttpRequest object, you can use HttpRequest.getCookies(), which returns an array of Cookie objects representing all the cookies included in the request. Although The CodeNotes Web site doesn't use custom cookies, Listing 2 shows an example JSP application that builds and processes a cookie.

Listing 2. Hello.jsp

<%
response.setHeader("Cache-Control", "no-cache"); %>
<html>
   <body>
      <%
      String text="World";
      Cookie[] cookies = request.getCookies();
      if (cookies.length != 0) {
         text = cookies[0].getValue();
      }
      if (request.getParameter("name") != null) {
         text = request.getParameter("name");
         Cookie helloCookie = new Cookie("name",text);
         helloCookie.setSecure(false);
         helloCookie.setVersion(0);
         helloCookie.setMaxAge(60*60*24);
         response.addCookie(helloCookie);
      }
      %>
      Hello, <%=text%>!
   </body>
</html>

Our Hello.jsp example uses a cookie to remember the value of a name parameter passed into it. By default, the application prints the message, "Hello, World!" in the user's browser. If the HTTP request includes a name parameter (for example, http://hostname/hello.jsp?name=Craig) Hello.jsp would return the message, "Hello, Craig!" instead. If a name is provided this application also generates a cookie containing the value of the name parameter. The user's browser will store this cookie for a week, and calls to Hello.jsp during that week will automatically know the user's name even if he does not include it in his request. Note that we also turn off caching in the first line of the JSP, so that any change (or removal) of the name parameter in consecutive page calls will take effect immediately.

One final thing to note in Listing 2 is that cookie attributes can be modified using set methods such as setSecure (which indicates whether or not this cookie requires a secure protocol to be sent) and setMaxAge (which allows you to specify how long the cookie will last). Naturally, get methods are also available for returning the values of cookie attributes.

Cookies Run Through the JLCA

The Java Language Conversion Assistant (JLCA) converts cookie code nearly seamlessly. The only caveat, as you will see in the following example, is that obtaining parameters from the query string is done slightly differently in Microsoft® ASP.NET than it is in JSP.

Although the CodeNotes site does use a cookie to keep track of a single viewer preference, the code is fairly embedded and difficult to follow. Instead of looking at the CodeNotes site, we'll convert the simple JSP from Listing 2 into an ASP.NET application using the JLCA. You'll need to follow these steps:

  1. Run the Conversion Wizard in Microsoft Visual Studio® .NET, as usual.

  2. After conversion is complete, right-click Hello.aspx in the Solution Explorer and then click Set As Start Page. You may have noticed that there were several (four) conversion errors reported in the Conversion Report generated by the JLCA. Three of these must be dealt with before the application will function correctly.

  3. Change the two references toRequest.ParamstoRequest.QueryStringinstead. For example, the line

    if ((System.Object)
    Request.Params["name"] != null)
    

    should be changed to:

    if ((System.Object)
    Request.QueryString["name"] != null)
    

    The reason for this is that the JLCA converts the JSP method Request.getParameter() into a reference to the Request.Params collection. However, while getParameter() only examines the query string of an HTTP request, the Params collection is a combined collection of QueryString, Form, ServerVariables, and Cookies items. The fact that Cookies are included in this collection confuses the logic of the application, as the if loop will always execute after the first time a cookie is added. The QueryString object therefore must be used as a replacement for Params, as it is closer to the desired functionality of the original application in this case.

  4. Finally, you need to erase or comment out the following line:

    helloCookie.setVersion(0);
    

    ASP.NET does not support cookie versioning, and the newest version is always automatically used (RFC 2109). If you had used the HttpCookie.setComment() method, you would also have had to comment out the resulting line as ASP.NET does not support adding comments to cookies.

After completing the steps above, you can run your new ASP.NET application and see that it is functionally identical to the original JSP.

Cookies in ASP.NET

You may have noticed that when the JLCA generated ASP.NET code from a JSP, there were some complicated features included, such as a class named SupportClass that contained additional helper methods that are not necessary. The process of creating and reading cookies directly in ASP.NET is actually quite similar to JSP, and just as easy. Listing 3 shows a method called RespondToCookie() that can simply be added to your ASP.NET application's code-behind file.

Listing 3. RespondToCookie() method in ASP.NET

protected string RespondToCookie()
{
   string text = "World";
   HttpCookieCollection cookies = Request.Cookies;

   if (cookies["name"] != null)
   {
     text = cookies["name"].Value;
   }

   if (Request.QueryString["name"] != null) 
   {
      text = Request.QueryString["name"];
      HttpCookie helloCookie = new HttpCookie("name",text);
      Response.SetCookie(helloCookie);
   }

   return text;
}

As in JSP, the request and response from the client are encapsulated in two separate objects. In JSP, it was HttpRequest and HttpResponse; ASP.NET uses Request and Response.

RespondToCookie() performs exactly the same actions as the Java code in Hello.jsp (Listing 2 ), which are:

  1. Define a string, text, and assign it the default value, "World." If the client does not specify a name in its request and there is no cookie containing a previously used name, this is the value that will be returned by this method.
  2. Create an instance of an object to store the list of cookies found in the Request object. In our JSP code in Listing 2, we used an array of javax.servlet.http.Cookie objects. ASP.NET uses a special collection object called System.Web.HttpCookieCollection.
  3. Check to see if a name cookie has been included in the response. If there is one, assign its value to "text."
  4. If the request included a name parameter (in ASP.NET, a QueryString object), assign its value to text. Then, create a new name cookie with text as its value and include this cookie in the Response object. The user can now access this page without a name parameter, and the application will use the cookie to remember the name that was last used. In ASP.NET, cookies are encapsulated by HttpCookie objects. The constructor for an HttpCookie is just like the one for Cookie objects in JSP (that is, two strings as parameters, one the cookie name and the other the cookie value). To add a cookie to a Response object, we use the setCookie() method.
  5. At the end, we return a string that contains either: the value of an included name parameter (if one was included); the value of the name cookie (if one exists and if no name parameter was specified); or simply, "World" if no cookie or parameter was included in the request.

Assuming our Web application is called Hello.aspx, RespondToCookie() should be placed in the file Hello.aspx.cs. In Hello.aspx itself, we can add the code shown in Listing 4 to invoke the method and use its return value in an HTML paragraph.

Listing 4. Calling RespondToCookie() from hello.aspx

<p>Hello,
   <%Response.Write(RespondToCookie());%>!</p>

Notice that we used the Response.Write() method to output generated text in the ASPX file. ASP.NET also supports the<%= %>shortcut as seen in the JSP example; we could have simply used<%=RespondToCookie()%>instead.

As mentioned previously, cookies consist of a name-value pair and a series of attributes. In the JSP code example (Listing 2) we saw several examples of methods that can be used to manipulate these attributes in a Cookie object. In ASP.NET, HttpCookie objects expose several properties with comparable functions, the values of which can be manipulated or retrieved.

Table 1 shows a list of comparable set methods for cookie attributes in JSP and properties in cookie attributes in ASP.NET, with a description of each. (Note that each of the JSP set methods has a corresponding get method.)

Table 1. Methods for Cookie Attributes

JSP Method ASP.NET Properties Description
setComment(java.lang.string purpose) N/A Sets or gets a comment about the purpose of the cookie.
SetDomain(java.lang.String pattern) string HttpCookie.Domain Sets or gets the domain associated with the cookie. Default is creation domain.
SetMaxAge(int expiry) System.DateTime HttpCookie.Expires Sets or gets the life span of the cookie. JSP is an integer representing length of time in seconds. ASP.NET is a dateTime of expiry.
setPath(java.lang.String uri) string HttpCookie.Path Sets or gets the path to which the client will send the cookie.
setSecure(boolean flag) bool HttpCookie.Secure Indicates whether or not the cookie requires secure protocols (HTTPS or SSL).
SetVersion(int v) N/A Sets or gets the cookie version. (0 is original specification, 1 is RFC 2109 specification.)

Summary

Cookies in both JSP and ASP.NET are straightforward to create, distribute, and read. The interfaces in both APIs are quite similar, as they both implement the same cookie specification. The slight differences in the cookie interface of ASP.NET (for example, cookies in requests are stored in name-value collections instead of simple arrays) actually give ASP.NET an advantage over JSP, allowing you to access cookies by name instead of having to iterate through them by number.

The JLCA converts cookies almost directly, except that it translates the getParameter() method into a much more general collection (the Params collection), and it does not recognize version or comment attributes. Both of these minor issues are easily overcome by changing a few lines of code.

Additional documentation of ASP.NET HttpCookie and HttpCookieCollection objects is available from:

© Microsoft Corporation. All rights reserved.