次の方法で共有


Maintaining Session State with Cookies

HTTP is a stateless protocol. This means that user data is not persisted from one Web page to the next in a Web site. One way to maintain state is through the use of cookies. Cookies store a set of user specific information, such as a reference identifier for a database record that holds customer information. 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.

Warning

Store no sensitive or secure data in cookies or other headers that are sent in the response. An example of sensitive data is customer user names, passwords, or credit card numbers. Malicious users can use tools that watch Internet traffic for this kind of information.

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.

Creating and Accessing 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 %>  
 </b>  
 </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 cookies again. 
     </P> 

   <% End If %> 

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

Creating and Accessing 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.

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>