Share via


Module Three: Maintaining Session State

Module three describes the process of maintaining session state in Active Server Pages (ASP). Session refers to the time segment that a specific user is actively viewing the contents of a Web site. A session starts when the user visits the first page on the site, and it ends a few minutes after the user leaves the site. The pieces of user-specific information, relevant to a particular session, are collectively known as session state.

Because HTTP is a stateless protocol, a problem arises when trying to maintain state for a user visiting your Web site. The Web server treats each HTTP request as a unique request, which is unrelated to any previous requests. Thus, the information a user enters on one page (through a form, for example) is not automatically available on the next page requested. The Web server must maintain session state to identify and track users as they browse through pages on a Web site.

One solution is through the use of cookies. Cookies record information about a user on one page and transfer that information to other pages within the site. However, a few browsers do not recognize cookies, and on other browsers, users can disable cookies. If you are concerned about reaching this Web audience, you can maintain session state without using cookies by using HTTP POST.

This module includes the following lessons:

  • Maintaining Session State with Cookies: Provides two cookie examples, one using the ASP Response and Request objects and another using the ASP Session object.
  • Maintaining Session State Without Cookies: Provides an example of the alternative to maintaining session state with cookies: HTTP POST.

Maintaining Session State with Cookies

Cookies store a set of user specific information, such as a credit card number or a password. The Web server embeds the cookie into a user's Web browser so that the user's information becomes available to other pages within the site; users do not have to reenter their information for every page they visit. Cookies are a good way to gather customer information for Web-based shopping, for retaining the personal preferences of the Web user, or for maintaining state about the user.

There are two kinds of cookies, as follows:

  • In-memory cookies: An in-memory cookie goes away when the user shuts the browser down.
  • Persistent cookies: A persistent cookie resides on the hard drive of the user and is retrieved when the user comes back to the Web page.

If you create a cookie without specifying an expiration date, you are creating an in-memory cookie, which lives for that browser session only. The following illustrates the script that would be used for an in-memory cookie:

   Response.Cookies("SiteArea") = "TechNet"

If you want the cookie information to persist beyond the session, you should create a persistent cookie by specifying an expiration date. Supplying an expiration date causes the browser to save the cookie on the client computer. Until the cookie expiration date is reached, the data in the persistent cookie will stay on the client machine. Any request to the original Web site will automatically attach the cookie that was created by that site. Cookies go only to the sites that created them because part of the Web site name and ASP file make up the data in the cookie. The following illustrates the script used to create a persistent cookie:

   Response.Cookies("SiteArea") = "TechNet"
   Response.Cookies("SiteArea").Expires = "August 15, 2000"

The script to create a cookie should be placed at the beginning of the ASP file because cookies need to be generated before any HTML text is sent to the browser.

Cookies Using the Response and Request Objects

Persistent cookies are produced using the Response and Request objects, although these objects may also be used to create an in-memory cookie. The majority of Web applications employ these objects to maintain session state.

  • Response object: Use the Response object to create and set cookie values.
  • Request object: Use the Request object to retrieve the value of a cookie created during a previous Web session.

In this lesson you will use the Response and Request objects to create the following files. Please create them all at once, because some of them need the others. After you have created all the files, run the application by typing https://LocalHost/Tutorial/Frame.htm in your browser.

  • Frame.htm: A page that splits the user's view into two windows. This page requires that Menu.htm and CustomGreeting.asp.
  • Menu.htm: A page containing links to the samples for this lesson. For the links to work, this page requires that all the other pages have been created.
  • CustomGreeting.asp: An ASP script that takes the user's name in a form and sets an in-memory cookie.
  • DeleteGreetingCookie.asp: An ASP script that deletes the cookie that contains the user's name. If no cookie is set, a warning is displayed.
  • SelectColors.asp: An ASP script that sets up the cookies for the user's color choices.
  • DeleteColorCookie.asp: An ASP script that deletes the Web colors previously chosen. If none are chosen, a warning is displayed.
  • Cookie.asp: An ASP script that sets persistent cookies to hold the current date and time of the user's visit and record the total number of visits.
  • DeleteCookies.asp: This ASP script deletes the cookies set in Cookie.asp. If no cookies are set, a warning is displayed.

Frame.htm

Open a new file in your text editor, paste in the following script, and save the file as C:\Inetpub\Wwwroot\Tutorial\Frame.htm.

   <html>
  <head>
  <title>Customized Greeting and Colors Using In-Memory and Persistent Cookies</title> 
  </head>

  <frameset cols="40%,60%">
    <frame src="menu.htm" name="left" marginheight="5" marginwidth="5">
    <frame src="CustomGreeting.asp" name="right" marginheight="5" marginwidth="5">
  </frameset>

  <noframes>
    Sorry, your browser does not support frames.  Please go to the <a href="menu.htm">Menu</a>.
  </noframes>

  </html>

Open a new file in your text editor, paste in the following script, and save the file as C:\Inetpub\Wwwroot\Tutorial\Menu.htm.

   <html>
  <head>
  <title>Maintaining Session State With Cookies</title>
  </head>
  <body>
  <font face="MS Gothic">

  <h2 align="center">Cookie Examples</h2>

  <table align=center border=1 cellpadding=4>
    <tr>
    <td><a href="CustomGreeting.asp" target="right"><b>Custom Greeting Page</b></a></td>
    </tr><tr>
    <td><a href="DeleteGreetingCookie.asp" target="right"><b>Delete the Greetings Cookie</b></a></td>
    </tr><tr>
    <td><a href="SelectColors.asp" target="right"><b>Set Page Colors</b></a></td>
    </tr><tr>
    <td><a href="DeleteColorCookie.asp" target="right"><b>Delete Page Colors Cookies</b></a></td>
    </tr><tr>
    <td><a href="Cookie.asp" target="right"><b>Set Cookies for Date, Time and Total Visits</b></a></td>
    </tr><tr>
    <td><a href="DeleteCookies.asp" target="right"><b>Delete Cookies for Date, Time and Total Visits</b></a></td>
    </tr>
  </table>

  </font>
  </body>
  </html>

CustomGreeting.asp

Open a new file in your text editor, paste in the following script, and save the file as C:\Inetpub\Wwwroot\Tutorial\CustomGreeting.asp.

   <%@ Language="VBScript" %> 
   <% 
   'If the user has selected text and background colors, 
   ' cookies are used to remember the values between HTTP sessions.
   'Do this first so that your page can use use the values if they are set.
   If Not (Server.HTMLEncode(Request.QueryString("Text"))="") Then 
     Response.Cookies("TextColor") = Server.HTMLEncode(Request.QueryString("Text")) 
     Response.Cookies("BackgroundColor") = Server.HTMLEncode(Request.QueryString("Background")) 
   End If 

   ' If the user has typed in a name, a cookie is created. 
   If Not (Server.HTMLEncode(Request.QueryString("Name"))="") Then 
     Response.Cookies ("Name") = Server.HTMLEncode(Request.QueryString("Name"))

   ' If the user does not give his/her name, a cookie 
   ' is created so that we do not keep asking for the name. 
   ElseIf (InStr(Server.HTMLEncode(Request.QueryString,"Name"))=1) Then 
     Response.Cookies ("NoUserInput") = "TRUE" 

   End If 
  %> 

  <html> 
  <head> 
  </head> 

  <%
   'Set colors according to existing previous user input.
   If (Server.HTMLEncode(Request.Cookies("TextColor"))="") Then %> 
     <body> 
   <% Else %> 
     <body bgcolor=<%=Server.HTMLEncode(Request.Cookies("BackgroundColor"))%> text=<%=Server.HTMLEncode(Request.Cookies("TextColor"))%>> 
   <% End If
  %>

  <font face="MS Gothic">

  <%
   'If there is no name cookie set, no name entered by the user, 
   ' and there was no user input at all, get the user's name.
   If ( (Server.HTMLEncode(Request.Cookies("Name"))="") And ((Server.HTMLEncode(Request.QueryString("Name")))="")) And (Not(Server.HTMLEncode(Request.Cookies("NoUserInput"))="TRUE") ) Then %>

     <FORM ACTION="CustomGreeting.asp" METHOD="GET" NAME="DataForm">
     <table align=center><tr><td>
     <INPUT TYPE=TEXTBOX NAME="Name" SIZE=33></td></tr><tr><td>
     <INPUT TYPE=Submit VALUE="Please Enter Your Name"></td></tr></table>
     </FORM> 

   <% ElseIf Not(Server.HTMLEncode(Request.Cookies("Name"))="") Then %>

     <H2 align=center>Greetings <%=Server.HTMLEncode(Request.Cookies("Name"))%></H2>

   <% Else %>

     <H2>Hello!</H2> 
     <H3>You did not give us your name so we are not able to greet you by name.</H3> 

   <% End If
  %> 

  <H3>In-Memory Cookie Example</H3>
  <P>
  Once you enter your name:
  <UL>
  <LI>If you hit <B>Refresh</B> in your browser, you should still see your name.</LI>
  <LI>If you close your browser, the cookie is deleted. When you re-open your browser to this page, you should be asked for your name again.</LI>
  <LI>If you click <B>Delete the Greetings Cookie</B>, and click <B>Custom Greeting Page</B>, you should be asked for your name again.</LI>
  </P>

  </font>
  </body> 
  </html> 

DeleteGreetingCookie.asp

Open a new file in your text editor, paste in the following script, and save the file as C:\Inetpub\Wwwroot\Tutorial\DeleteGreetingCookie.asp.

<%@ Language="VBScript" %> <html> <head> </head> <% If (Server.HTMLEncode(Request.Cookies("TextColor"))="") Then %> <body> <font face="MS Gothic"> <% Else %> <body bgcolor=<%=Server.HTMLEncode(Request.Cookies("BackgroundColor"))%> text=<%=Server.HTMLEncode(Request.Cookies("TextColor"))%>> <font face="MS Gothic" color=<%=Server.HTMLEncode(Request.Cookies("TextColor"))%>> <% End If %> <% If Not ("" = Server.HTMLEncode(Request.Cookies("Name"))) Then Response.Cookies ("Name").Expires = "January 1, 1992" Response.Cookies ("NoUserInput").Expires = "January 1, 1992" %> <h2 align=center>In-Memory Greeting Cookie Deleted</h2> <P> The cookie used to keep track of your name has been deleted.<BR> Please click <B>Custom Greeting Page</B> to be asked for your name again. </P> <% Else %> <h2 align=center>No In-Memory Greeting Cookie Deleted</h2> <P> There was no cookie set with your name.<BR> Please click <B>Custom Greeting Page</B> to enter your name. </P> <% End If %> </font> </body> </html>

SelectColors.asp

Open a new file in your text editor, paste in the following script, and save the file as C:\Inetpub\Wwwroot\Tutorial\SelectColors.asp.

   <%@ Language="VBScript" %> 

  <% 
    ' If the user has selected text and background colors, 
    ' cookies are used to remember the values between HTTP sessions. 
    If Not (Server.HTMLEncode(Request.QueryString("Text"))="") Then 
      Response.Cookies ("TextColor") = Server.HTMLEncode(Request.QueryString("Text")) 
      Response.Cookies ("BackgroundColor") = Server.HTMLEncode(Request.QueryString("Background")) 
    End If 
  %> 

  <html> 
  <head> 
  </head> 

  <%
    'Set colors according to existing previous user input.
    If (Server.HTMLEncode(Request.Cookies ("TextColor"))="") Then %> 
     <body> 
    <% Else %> 
     <body bgcolor=<%=Server.HTMLEncode(Request.Cookies("BackgroundColor"))%> text=<%=Server.HTMLEncode(Request.Cookies("TextColor"))%>>
    <% End If
  %> 

  <font face="MS Gothic"> 

  <H2 align=center>Select the colors for your Web page</H2>
  <P>
  In Memory Cookies will be used to store these values.
  </P>
  <FORM ACTION="SelectColors.asp" METHOD="GET" NAME="DataForm">
  <table border="1" width="450" cellpadding=0>
  <tr><td>
    <table>
    <tr><td BGCOLOR=99FF99>
    <B><font color=000000>Please select the background color</font></B>
    </td></tr><tr><td BGCOLOR=FFFFFF>
    <input type="RADIO" NAME="Background" VALUE="FFFFFF" CHECKED><font COLOR=000000> FFFFFF </font>
    </td></tr><tr><td BGCOLOR=D98719>
    <input type="RADIO" NAME="Background" VALUE="D98719"> D98719
    </td></tr><tr><td BGCOLOR=D9D919>
    <input type="RADIO" NAME="Background" VALUE="D9D919"> D9D919
    </td></tr><tr><td BGCOLOR=00FFFF>
    <input type="RADIO" NAME="Background" VALUE="00FFFF"> 00FFFF
    </td></tr><tr><td BGCOLOR=FF00FF>
    <input type="RADIO" NAME="Background" VALUE="FF00FF"> FF00FF
    </td></tr><tr><td BGCOLOR=000000> 
    <input type="RADIO" NAME="Background" VALUE="000000"> <font COLOR=FFFFFF>000000</font>
    </td></tr> 
  </table>
  </td><td> 
    <table> 
    <tr><td BGCOLOR=99FF99> 
    <B><font color=000000>Please select the text color</font></B> 
    </td></tr><tr><td BGCOLOR=FFFFFF> 
    <input type="RADIO" NAME="Text" VALUE="FFFFFF" CHECKED><font COLOR=000000> FFFFFF </font>
    </td></tr><tr><td BGCOLOR=D98719> 
    <input type="RADIO" NAME="Text" VALUE="D98719"> D98719 
    </td></tr><tr><td BGCOLOR=D9D919> 
    <input type="RADIO" NAME="Text" VALUE="D9D919"> D9D919 
    </td></tr><tr><td BGCOLOR=00FFFF> 
    <input type="RADIO" NAME="Text" VALUE="00FFFF"> 00FFFF 
    </td></tr><tr><td BGCOLOR=FF00FF> 
    <input type="RADIO" NAME="Text" VALUE="FF00FF"> FF00FF 
    </td></tr><tr><td BGCOLOR=000000> 
    <input type="RADIO" NAME="Text" VALUE="000000" CHECKED><font COLOR=FFFFFF> 000000 </font>
    </td></tr> 
     </table> 
  </td></tr> 
  </table>
  <P>
  <input type=Submit VALUE="Submit selected colors"> 
  </FORM> 

  </font>
  </body> 
  </html> 

DeleteColorCookie.asp

Open a new file in your text editor, paste in the following script, and save the file as C:\Inetpub\Wwwroot\Tutorial\DeleteColorCookie.asp.

   <%@ Language="VBScript" %> 

  <html> 
   <head> 
   </head> 
   <body> 
   <font face="MS Gothic">

   <% 
   If Not ("" = Server.HTMLEncode(Request.Cookies("TextColor"))) Then
     Response.Cookies("TextColor").Expires = "January 1, 1992" 
     Response.Cookies("BackgroundColor").Expires = "January 1, 1992" %>

     <h2 align=center>In-Memory Color Cookie Deleted</h2> 
     <P> 
     The cookie used to keep track of your display colors has been deleted.<BR>
     Please click <B>Set Page Colors</B> to set your colors again.
     </P>

   <% Else %>

     <h2 align=center>No In-Memory Color Cookie Deleted</h2> 
     <P>
     There was no cookie set with your color choices.<BR>
     Please click <B>Set Page Colors</B> to set display colors.
     </P>

   <% End If
   %>

   </font>
   </body> 
   </html>

Cookie.asp

Open a new file in your text editor, paste in the following script, and save the file as C:\Inetpub\Wwwroot\Tutorial\Cookie.asp.

   <%@ Language="VBScript" %> 

  <%
   LastAccessTime = Server.HTMLEncode(Request.Cookies("LastTime"))
   LastAccessDate = Server.HTMLEncode(Request.Cookies("LastDate"))

   'If the NumVisits cookie is empty, set to 0, else increment it.
   If (Server.HTMLEncode(Request.Cookies("NumVisits"))="") Then 
     Response.Cookies("NumVisits") = 0 
   Else 
     Response.Cookies("NumVisits") = Server.HTMLEncode(Request.Cookies("NumVisits")) + 1 
   End If 

   Response.Cookies("LastDate") = Date
   Response.Cookies("LastTime") = Time

   'Setting an expired date past the present date creates a persistent cookie.
   Response.Cookies("LastDate").Expires = "January 15, 2001"
   Response.Cookies("LastTime").Expires = "January 15, 2001"
   Response.Cookies("NumVisits").Expires = "January 15, 2001"
  %> 

  <html> 
  <head> 
  </head> 
  <% If (Server.HTMLEncode(Request.Cookies ("TextColor"))="") Then %> 
     <body>
     <font face="MS Gothic">
  <% Else %> 
     <body bgcolor=<%=Server.HTMLEncode(Request.Cookies("BackgroundColor"))%> text=<%=Server.HTMLEncode(Request.Cookies("TextColor"))%>>
     <font face="MS Gothic" color=<%=Server.HTMLEncode(Request.Cookies("TextColor"))%>>
  <% End If %>

  <H2 align=center>Persistent Client-Side Cookies!</H2> 

  <P>
  Three persistent client-side cookies are created.
  <UL>
  <LI>A cookie to count the number of times you visited the Web page.</LI>
  <LI>A cookie to determine the date of your visit.</LI>
  <LI>A cookie to determine the time of your visit.</LI>
  </UL>
  </P> 

 <table border="1" width="300" cellpadding=4 align=center> 
 <tr><td>
 <% If (Server.HTMLEncode(Request.Cookies ("NumVisits"))=0) Then %> 
    Welcome! This is your first visit to this Web page! 
 <% Else %> 
    Thank you for visiting again! You have been to this Web page a total of <B><%=Server.HTMLEncode(Request.Cookies("NumVisits"))%></B> time(s).
 <% End If %> 
 </td></tr>
 </table> 

 <P> 
 <B>The Current time is <%=Time%> on <%=Date%><BR>
 <% If (Server.HTMLEncode(Request.Cookies ("NumVisits"))>0) Then %> 
     You last visited this Web page at <%=LastAccessTime%> on <%=LastAccessDate%> 
 <% End If %> 
 </strong> 
 </P>

 </font>
 </body> 
 </html> 

DeleteCookies.asp

Open a new file in your text editor, paste in the following script, and save the file as DeleteCookies.asp.

   <%@ Language="VBScript" %> 

  <html>
  <head> 
  </head> 

  <% If (Server.HTMLEncode(Request.Cookies ("TextColor"))="") Then %> 
     <body>
     <font face="MS Gothic">
  <% Else %> 
     <body bgcolor=<%=Server.HTMLEncode(Request.Cookies("BackgroundColor"))%> text=<%=Server.HTMLEncode(Request.Cookies("TextColor"))%>>
     <font face="MS Gothic" color=<%=Server.HTMLEncode(Request.Cookies("TextColor"))%>>
  <% End If %>

  <%
   If Not ("" = Server.HTMLEncode(Request.Cookies("NumVisits"))) Then
     Response.Cookies("NumVisits").Expires = "January 1, 1993"
     Response.Cookies("LastDate").Expires = "January 1, 1993" 
     Response.Cookies("LastTime").Expires = "January 1, 1993" %>

     <H2 align=center>Persistent Cookies Are Deleted</H2>
     <P>
     The cookies used to keep track of your visits and date and time of last visit have been deleted.<BR>
     Please click <B>Set Cookies for Date, Time and Total Visits</B> to set your cookies again.
     </P>

   <% Else %>
 
     <H2 align=center>No Persistent Cookies Are Deleted</H2>
     <P>
     There were no cookies set to keep track of your visits, and date and time of last visit.<BR>
     Please click <B>Set Cookies for Date, Time and Total Visits</B> to set your colors again.
     </P>

   <% End If %>

  </font>
  </body> 
  </html> 

Cookies Using the Session Object

With the Session object, you can create only an in-memory cookie. For the Session object to work correctly, you need to determine when a user's visit to the site begins and ends. IIS does this by using a cookie that stores an ASP Session ID, which is used to maintain a set of information about a user. If an ASP Session ID is not present, the server considers the current request to be the start of a visit. The visit ends when there have been no user requests for ASP files for the default time period of 20 minutes.

In this lesson, you will create the following:

  • Global.asa: Global.asa is a file that allows you to perform generic actions at the beginning of the application and at the beginning of each user's session. An application starts the first time the first user ever requests a page and ends when the application is unloaded or when the server is taken offline. A unique session starts once for each user and ends 20 minutes after that user has requested their last page. Generic actions you can perform in Global.asa include setting application or session variables, authenticating a user, logging the date and time that a user connected, instantiating COM objects that remain active for an entire application or session, and so forth.
  • VisitCount.asp: This ASP script uses the Session object to create an in-memory cookie.

When an application or session begins or ends, it is considered an event. Using the Global.asa file, you can use the predefined event procedures that run in response to the event.

Global.asa

Open a new file in your text editor, paste in the following script, and save the file in your root directory as C:\Inetpub\Wwwroot\Global.asa.

important Important Global.asa files must be saved in the root directory of the application for ASP to find it. If you had a virtual path called Test mapped to C:\Inetpub\Wwwroot\Test, your URL would be https://LocalHost/Test, and the Global.asa file would have to go in C:\Inetpub\Wwwroot\Test. We did not create a virtual path mapped to C:\Inetpub\Wwwroot\Tutorial, so our root directory is still C:\Inetpub\Wwwroot.

   <SCRIPT LANGUAGE=VBScript RUNAT=Server>

  'Using application-level variables to track the number of users 
   ' that are currently looking at the site and the number that have 
   ' accessed the site. 
   Sub Application_OnStart

    'Get the physical path to this vdir, and append a filename.
    Application("PhysPath") = Server.MapPath(".") & "\hits.txt"

    'Set some Visual Basic constants, and instantiate the FileSystemObject object.
    Const cForReading = 1
    Const cTristateUseDefault = -2
    Set fsoObject = Server.CreateObject("Scripting.FileSystemObject")

    'Get the last saved value of page hits and the date that it happened.
    If fsoObject.FileExists(Application("PhysPath")) Then

       'If the file hits.txt exists, set the Application variables.  
       Set tsObject = fsoObject.OpenTextFile(Application("PhysPath"), cForReading, cTristateUseDefault)
       Application("HitCounter") = tsObject.ReadLine
       Application("AppStartDate") = tsObject.ReadLine
       tsObject.Close  

    Else 'No file has been saved, so reset the values.

       Application("HitCounter") = 0
       Application("AppStartDate") = Date

    End If

    Application("CurrentUsers") = 0

   End Sub


   Sub Application_OnEnd 

    Const cForWriting = 2
    Const cTristateUseDefault = -2

    Set fsoObject = Server.CreateObject("Scripting.FileSystemObject")
    If fsoObject.FileExists(Application("PhysPath")) Then

       'If the file exists, open it for writing.
       set tsObject = fsoObject.OpenTextFile(Application("PhysPath"), cForWriting, cTristateUseDefault)

    Else

       'If the file doesn't exist, create a new one. 
       set tsObject = fsoObject.CreateTextFile(Application("PhysPath"))

    End If

    'Write the total number of site hits and the last day recorded to the file.
    tsObject.WriteLine(Application("HitCounter"))
    tsObject.WriteLine(Application("AppStartDate"))
    tsObject.Close  

   End Sub 


   Sub Session_OnStart 

    'The Session time-out default is changed to 1 for the purposes of 
    ' this example.
    Session.Timeout = 1 

    'When you change Application variables, you must lock them so that other 
    ' sessions cannot change them at the same time.
    Application.Lock

    'Increment the site hit counter.
    Application("HitCounter") = Application("HitCounter") + 1   
    Application("CurrentUsers") = Application("CurrentUsers") + 1

    Application.UnLock

   End Sub 


   Sub Session_OnEnd 

    Application.Lock

    'Decrement the current user counter.
    Application("CurrentUsers") = Application("CurrentUsers") - 1

    Application.UnLock

   End Sub 

   </SCRIPT> 

VisitCount.asp

You can use variables set in Global.asa to measure visits and sessions.

Open a new file in your text editor, paste in the following script, and save the file as C:\Inetpub\Wwwroot\Tutorial\VisitCount.asp. View the file in your browser by typing https://Localhost/Tutorial/VisitCount.asp.

Open a second instance of the browser to https://Localhost/Tutorial/VisitCount.asp, and click Refresh on the first browser. Total Visitors and Active Visitors should increase by one. Close down the second browser, wait over a minute, and click Refresh on the first browser. Active Visitors should decrease by one.

   <% Response.Buffer = True%> 

  <html> 
  <head> 
  <title>Retrieving Variables Set in Global.asa</title> 
  </head> 
  <body> 
  <font face="MS Gothic">

  <H3 align=center>Retrieving Variables Set in Global.asa</H3>
  <P>
  Total Visitors = <%=Application("HitCounter")%> since <%=Application("AppStartDate")%><BR>
  Active Visitors = <%=Application("CurrentUsers")%>
  </P>

  </font>
  </body> 
  </html> 

Maintaining Session State Without Cookies

Some browsers do not recognize cookies, and users can choose to disable cookies in their browsers. The HTTP POST method provides an alternative to cookies to maintain session state. The HTTP POST method provides the same state information as would a cookie but has the advantage that it works even when cookies are not available. This method is not common in practice, but it is a good example to learn from. The HTTP POST method works similarly to an in-memory cookie; user information can be maintained only during the visit, and the session state information is gone when the user turns off the browser.

DataEntry.asp

Open a new file in your text editor, paste in the following script, and save the files as C:\Inetpub\Wwwroot\Tutorial\DataEntry.asp. View the file in your browser by typing https://Localhost/Tutorial/DataEntry.asp.

   <%@ Language=VBScript %> 

  <html> 
  <head> 
  <title>Data Entry Without Cookies</title> 
  </head> 
  <body>
  <font face="MS Gothic">

  <!-- In this example, subroutines are listed first. 
       There's a subroutine for each page of the order process.
       The main calling code is at the bottom. --> 

  <% Sub DisplayInitialPage %>

    <table border=1 cellpadding=3 cellspacing=0 width=500 bordercolor=#808080 align=center> 
    <tr><td bgColor=#004080 align=center> 
    <font color=#ffffff><H2>Order Form</H2></font> 
    </td></tr><tr><td bgColor=#e1e1e1 align=left> 
    <P><B>Step 1 of 4</B></P>
    <P align=center>
    This form uses the HTTP POST method to pass along hidden values that contain 
    your order information. This form does not use cookies.  <b>DO NOT ENTER CREDIT CARD 
    INFORMATION UNLESS YOU SEE HTTPS:// IN THE ADDRESS BAR OF YOUR WEB BROWSER, AS THIS INDICATES A 
    SECURE SOCKETS LAYER (SSL) CONNECTION.</b>
    </P> 

    <FORM METHOD=POST ACTION="DataEntry.asp" NAME=DataEntryForm> 
    <P>Enter your name 
    <INPUT TYPE="TEXT" NAME=FullName> 
    <BR>Enter your imaginary credit card number 
    <INPUT TYPE="TEXT" NAME=CreditCard>
    </P> 
    <!-- Keeps track of the information by using the hidden HTML form variable Next Page. --> 
    <INPUT TYPE="HIDDEN" NAME=NextPage VALUE=2> 
    <INPUT TYPE="SUBMIT" VALUE="Next ->" NAME=NextButton> 
    </FORM> 

    </td></tr> 
    </table>

  <% End Sub %>


  <% Sub DisplayDogBreed %>

    <table border=1 cellpadding=3 cellspacing=0 width=500 align=center> 
    <tr><td bgColor=#004080 align=center> 
    <font color=#ffffff><H2>Order Form</H2></font> 
    </td></tr><tr><td bgColor=#e1e1e1> 
    <P><B>Step 2 of 4</B></P>
    <P align=center>
    Please select the type of dog you want. 
    </P> 

    <FORM METHOD=POST ACTION="DataEntry.asp" NAME=DataEntryForm>
    <P>
    <INPUT TYPE=RADIO NAME=DogSelected VALUE="Cocker Spaniel" CHECKED>Cocker Spaniel<BR>
    <INPUT TYPE=RADIO NAME=DogSelected VALUE="Doberman">Doberman<BR>
    <INPUT TYPE=RADIO NAME=DogSelected VALUE="Timber Wolf">Timber Wolf<BR>
    <INPUT TYPE=RADIO NAME=DogSelected VALUE="Mastiff">Mastiff<BR>
    </P>
    <!--Keeps track of the information by using the hidden HTML form variable Next Page. --> 
    <INPUT TYPE="HIDDEN" NAME=NextPage VALUE=3>
    <INPUT TYPE="SUBMIT" VALUE="Next ->" NAME=NextButton> 
    </FORM> 
    </td></tr>
    </table> 

  <% End Sub %>


  <% Sub DisplayCity %> 

    <table border=1 cellpadding=3 cellspacing=0 width=500 align=center> 
    <tr><td bgColor=#004080 align=center> 
    <font color=#ffffff><H2>Order Form</H2></font> 
    </td></tr><tr><td bgColor=#e1e1e1> 
    <P><B>Step 3 of 4</B></P>
    <P align=center>
    We deliver from the following cities. Please choose the one closest to you.
    </P> 

    <FORM METHOD=POST ACTION="DataEntry.asp" NAME=DataEntryForm>
    <P>
    <INPUT TYPE=RADIO NAME=CitySelected VALUE="Seattle" CHECKED>Seattle<BR>
    <INPUT TYPE=RADIO NAME=CitySelected VALUE="Los Angeles">Los Angeles<BR>
    <INPUT TYPE=RADIO NAME=CitySelected VALUE="Boston">Boston<BR>
    <INPUT TYPE=RADIO NAME=CitySelected VALUE="New York">New York<BR>
    </P>
    <!--Keeps track of the information by using the hidden HTML form variable Next Page. --> 
    <INPUT TYPE="HIDDEN" NAME=NextPage VALUE=4>
    <INPUT TYPE="SUBMIT" VALUE="Next ->" NAME=NextButton> 
    </FORM> 
    </td></tr>
    </table> 

  <% End Sub %>


  <% Sub DisplaySummary %>

    <table border=1 cellpadding=3 cellspacing=0 width=500 align=center> 
    <tr><td bgColor=#004080 align=center> 
    <font color=#ffffff><H2>Order Form Completed</H2></font> 
    </td></tr><tr><td bgColor=#e1e1e1> 
    <P><B>Step 4 of 4</B></P>
    <P align=center>
    The following information was entered.<BR> 
    A transaction will now be executed to complete your order if your name and 
    credit card are valid.
    </P> 
      <table cellpadding=4> 
      <tr bgcolor=#ffffcc><td>
      Name
      </td><td>
      <%=Session.Value("FullName")%> 
      </td></tr><tr bgcolor=Beige><td>
      Credit Card 
      </td><td>
      <%=Session.Value("CreditCard")%> 
      </td></tr><tr bgcolor=Beige><td>
      Dog Ordered 
      </td><td>
      <%=Session.Value("DogSelected")%>
      </td></tr><tr bgcolor=Beige><td>
      City Ordered From 
      </td><td>  
      <%=Session.Value("CitySelected")%>
      </td></tr> 
      </table> 
    </td> 
    </tr> 
    </table> 

  <% End Sub %>


  <% Sub StoreUserDataInSessionObject  %>
  <%
    Dim FormKey
    For Each FormKey in Request.Form
    Session(FormKey) = Server.HTMLEncode(Request.Form.Item(FormKey))
    Next 
  %>
  <% End Sub  %>


  <%
    'This is the main code that calls all the subroutines depending on the
    ' hidden form elements.

    Dim CurrentPage 

    If Server.HTMLEncode(Request.Form.Item("NextPage")) = "" Then
      CurrentPage = 1 
    Else
      CurrentPage = Server.HTMLEncode(Request.Form.Item("NextPage"))
    End If 

    'Save all user data so far.
    Call StoreUserDataInSessionObject

    Select Case CurrentPage 
      Case 1 : Call DisplayInitialPage 
      Case 2 : Call DisplayDogBreed 
      Case 3 : Call DisplayCity 
      Case 4 : Call DisplaySummary 
    End Select %> 

  <BR> 
  <H3 align=center><A HREF="DataEntry.asp">Reset Order</A></H3> 

  </font>
  </body> 
  </html> 

In the browser, you should see the following:


Order Form

Step 1 of 4

This form uses the HTTP post method to pass along hidden values that contain your order information. This form does not use cookies. DO NOT ENTER CREDIT CARD INFORMATION UNLESS YOU SEE HTTPS:// IN THE ADDRESS BAR OF YOUR WEB BROWSER, AS THIS INDICATES A SECURE SOCKETS LAYER (SSL) CONNECTION.

Enter your name Text box Enter your imaginary credit card number Text box

You have reached the end of the tutorial.

note Note Remember to experiment with the code. Make little changes and refresh the page in your browser to see the results.