Using Cookies
Yesterday's lesson discussed how cookies could be used to maintain simple state information
over long periods of times. Cookies are small text files written to the client's
computer. As you learned yesterday, cookies can be written to the client's computer
using the Response.Cookies collection and can be read using the Request.Cookies collection.
Cookies can persist on the client's computer for a variable amount of time. When
writing a cookie to the client's computer, you can set when the cookie expires. This
can be in a day, a week, or even a year. Cookies allow a user's state to be maintained
beyond the current visit. The section "Passing Information Through the Querystring" earlier today
looked at persisting a user's name throughout all the ASP pages on your Web site. Let's
examine how you can use cookies to maintain this information.
Listing 11.1 created a simple form in which the user was prompted to enter his or her
name. This form, when submitted, passed the user's name through the querystring to
Welcome.asp, the form processing script. Because you are going to use cookies to maintain
state in this example, you don't need to worry about having all the hyperlinks in
Welcome.asp passing along the querystring information. All you need to do in Welcome.asp
is write the name of the user to a cookie. Listing 11.4 shows Welcome.asp, modified to use
cookies to maintain the user's name.
Listing 11.4 - Using Cookies to Maintain State
1: <%@ Language=VBScript %>
2: <% Option Explicit %>
3: <%
4: 'Read in the Name from the form
5: Dim strName
6: strName = Request("Name")
7:
8: 'Write the user's name to a cookie
9: Response.Cookies("UserName") = strName
10:
11: 'Set the cookie to expire in a week
12: Response.Cookies("UserName").Expires = Date() + 7
13: %>
14:
15: <HTML>
16: <BODY>
17: Hello <%=strName%>!
18: <P>
19: What interests you?<BR>
20: <LI><A HREF="sports.asp">Sports</A><BR>
21: <LI><A HREF="politics.asp">Politics</A><BR>
22: <LI><A HREF="fashion.asp">Fashion</A><BR>
23: <LI><A HREF="events.asp">Current Events</A><BR>10: </BODY>
24: </HTML>
To maintain state using cookies, you only need to write the cookie to the client's
computer once: when the user enters the information that you want to persist. After the
user enters his or her name into the form created by Listing 11.1, Welcome.asp, shown
in Listing 11.4, is called. Line 6 starts off by reading the user's name into the
variable strName. Line 9 then creates a cookie named UserName and writes to it the
user's name. Line 12 sets the cookie to expire in seven days. Assuming that the user
accepts cookies, the user's name will be persisted for a week.
Line 17 simply print outs the personalized welcome message. Lines 20 through 23 create a
series of hyperlinks. Notice that with the cookie method you don't need to bother with
appending the current querystring to the hyperlinks. The output of Listing 11.4, when
viewed through a browser, is no different than that of Listing 11.2. The output can be
seen in Figure 11.3.
You can read the user's name from any other ASP page on your site by using the Request.Cookies
collection to access the UserName cookie. On each page that you wanted to display your
personalized greeting, you could simply add the following ASP code:
Recall from Day 10, that some people set their browsers to not accept cookies. If such
a person were to visit your site, his name would not be persisted. The only way
to persist information for these types of users is to use the querystring method
discussed in the earlier section "Passing Information Through the Querystring."
Using the Session Object
Active Server Pages comes with a built-in object to help developers maintain state on a
user-by-user basis. This object is called the Session object and can be accessed through
any ASP page on your Web site. The Session object can store any kind of data type, from
numbers and strings to arrays and objects!
The Session is used to maintain state only for the duration of a user's visit to your
Web site. When each new user comes to your site, memory on the Web server is allocated to
store the Session object for that user. This memory is released if the user does not
visit your Web site for a certain length of time. This time period is 10 minutes, by
default but can be set to a shorter or lengthier period. We will discuss the finer
details of the Session object in "The Session Object."
Each variable stored in the Session object is referred to as a session variable. You can
create session variables with the following syntax:
Session(sessionVariableName) = value
where sessionVariableName is a string. The following lines of code create a number of
session variables:
Line 1 creates a session variable named Today, which stores the current date. Line 2
creates a session variable named WelcomeMessage, which contains a string. Finally, line
3 stores a numeric value in the session variable named Age.
Each time you create a new variable in the Session object, that bit of memory for each
unique user increases, and the new variable is stored in that memory space. These variables
are persisted for each user as long as the user keeps making page requests of the Web
site. Therefore, the session variables can be used to maintain state.
In both the sections "Passing Information through the Querystring" and "Using Cookies," you saw an
example where the user would enter his or name. The name would then be shown in a
personalized greeting on each Web page. You already know how to accomplish this with cookies
and the querystring method - let's examine how you would use the Session object.
You only need to slightly modify the code in Listing 11.4 to use the Session object to
maintain state. Listing 11.5 contains the new code for Welcome.asp.
Listing 11.5 - Using the Session Object to Maintain State
1: <%@ Language=VBScript %>
2: <% Option Explicit %>
3: <%
4: 'Read in the Name from the form
5: Dim strName
6: strName = Request("Name")
7:
8: 'Write the user's name to a session variable
9: Session("UserName") = strName
10: %>
11:
12: <HTML>
13: <BODY>
14: Hello <%=strName%>!
15: <P>
16: What interests you?<BR>
17: <LI><A HREF="sports.asp">Sports</A><BR>
18: <LI><A HREF="politics.asp">Politics</A><BR>
19: <LI><A HREF="fashion.asp">Fashion</A><BR>
20: <LI><A HREF="events.asp">Current Events</A><BR>
21: </BODY>
22: </HTML>
To maintain state using the Session object, you need to create a session variable for
each bit of information that needs to be persisted. Because you only need to save the
user's name, you can use just one session variable. Listing 11.5 starts off by reading
in the name the user entered in the previous form (line 6). Next, on line 9, a single
session variable, named UserName, is created. This session variable is then assigned the
value of strName.
Lines 12 through 21 have not changed from Listing 11.4. Line 14 simply prints out a
personalized welcome message, whereas lines 17 through 20 create a series of hyperlinks.
Notice that when using session variables, you don't need to bother with appending the
current querystring to the hyperlinks. Again, the output of Listing 11.5, when viewed
through a browser, is no different from that of Listing 11.2 or Listing 11.4. The
output can be seen in Figure 11.3.
To obtain the user's name in any other ASP page on your Web site, all you have to do is
read the value of your session variable. Session variables are read using the following
syntax:
SomeVariable = Session(sessionVariableName)
You can display your personalized greeting on any ASP page with the following code:
The Session object uniquely identifies visitors via cookies. This means that session
variables will not persist across ASP pages if the user has cookies disabled. Once again,
the only sure-fire way to guarantee that state will be maintained for all your visitors is
to use the querystring method. However, because the vast majority of users accept
cookies, most Active Server Pages developers feel comfortable using cookies or the Session
object to maintain state. A more detailed discussion is dedicated to this matter later today
in the section "The Session Object."
Using the Application Object
The Application object is another intrinsic ASP object to help maintain state. You may
wonder how the Application and Session objects differ, if they both are designed to
maintain state on your Web site. Whereas the Session object is designed to maintain
state on a user-by-user basis, the Application object is designed to maintain state
globally, across the entire Web site. The Application object, like the Session object, can
store an assortment of variables of any type. Each variable stored in the Application
is referred to as an application variable.
Application variables are sometimes referred to as global variables because any user can
access any application variable from any ASP page. It is important to keep in mind that
there is only one instance of the Application object for your Web site. Every single user
to your Web site has access to the exact same set of application variables.
Imagine that two users visit your site and that there exists an application variable named
DefaultMessage, which contains the string Welcome to my Web site!. Imagine that the first
user visits an ASP page that changes the application variable DefaultMessage to Hello, there!.
After this change has been made, the second user visits another ASP page that displays
the application variable DefaultMessage. The second user will see Hello, there! through his browser.
Because there is only one instance of the Application object and because any user on
any ASP page can alter application variables, when the first user changes the value of
an application variable, the results are immediately noticed by the second user.
You may be wondering how the Application object can be used to maintain state. Because the
Application object is global among all users, you should not try to use application variables
to maintain state on a user-by-user basis. However, if you have some global piece of
information that you want to save for the entire Web site, application variables are
often the way to go, especially if the information changes often. We will discuss when and
how to use application variables in greater detail later today in the section
"The Application Object."
Do/Don't Box
DON'T store user-specific information in the Application object. If you need to store
information specific to each user, use the Session object instead.
Choosing the Approach that Works for You
So far we've examined the four methods of maintaining state. The first three approaches examined - using
the querystring, using cookies, and using session variables - can be used to maintain
state on a user-by-user basis. The final method discussed - using the Application object - can
be used to maintain Web site-wide state.
Now that you've studied the four methods of persisting state, which method should you
choose? Because each approach has strong points and weak points, the method to use
depends largely on the situation. Table 11.1 presents all four methods of maintaining
state and lists under what conditions to use what method.
Table 11.1 - Approaches to Maintaining State
Methods
When to Use
Querystring method
When using the querystring method to persist state, make sure that each hyperlink passes on the current querystring to the next ASP page. This leads to a maintenance headache. The nice thing about the querystring method, though, is that it doesn't require the user to have cookies enabled. If you need to persist simple data types for only the duration of the user's visit to the site and it is imperative that even users who have cookies disabled have their state maintained, then the querystring method is the way to go.
Cookies
If you need to maintain state for periods longer than the duration of the user's visit, then cookies are your only option. Cookies can only save simple data types (strings, numbers, dates) and can be rejected by the client's computer. Cookies, though, require no overhead on the Web server because they are stored on the client's machine. If performance is a big concern, or if you need to persist information for days, weeks, or months, then cookies are the best choice!
Session variables
If you only need to maintain state for the duration of your users' visits, using session variables may be the way to go. The Session object, unlike cookies, can store any variable type. However, the Session object resides on the Web server. If you receive many concurrent users or place large objects in the Session object, your Web server's performance will degrade. Session variables are the best choice when you need to maintain state only for the user's visit to your site.
Application variables
Application variables can be used to maintain information that is global to the entire Web site. The Application object should not be used to maintain state on a user-by-user basis. Application variables are a wise choice when you have some piece of information that changes often and that is global to the entire Web site. For example, if you ran a Web site that had a message board where users could post their questions, you might want to display on all your Web pages the time and date the last post was made. This information should be stored in an application variable because it changes often and is global to the Web site.
Now that we've examined four ways to maintain state, we are going to delve into the
Session and Application objects. Both of these built-in objects are useful but often
misused. Because the Session and Application objects reside on the Web server, misusing
these two objects can lead to a performance hit. The next two sections, "The Session Object"
and "The Application Object," discuss not only how to use these objects but also how
not to use these objects.