Home | | Internet & World Wide Web HOW TO PROGRAM | | Internet Programming | | Web Programming | Session Tracking and Cookies - Active Server Pages (ASP)

Chapter: Internet & World Wide Web HOW TO PROGRAM - Active Server Pages (ASP)

Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail

Session Tracking and Cookies - Active Server Pages (ASP)

HTTP does not support persistent information that could help a Web server distinguish be-tween clients. In this section, we introduce two related technologies that enable a Web serv-er to distinguish between clients: session tracking and cookies.

Session Tracking and Cookies

 

HTTP does not support persistent information that could help a Web server distinguish be-tween clients. In this section, we introduce two related technologies that enable a Web serv-er to distinguish between clients: session tracking and cookies.

 

Many Web sites provide custom Web pages or functionality on a client-by-client basis. For example, some Web sites allow you to customize their home page to suit your needs. An example of this is the Yahoo! Web site (my.yahoo.com), which allows you to cus-tomize how the Yahoo! site appears. [Note: You need to get a free Yahoo! ID first.]

Another example of a service that is customized on a client-by-client basis is a shop-ping cart for shopping on the Web. When a purchase is made, the server must distinguish between clients so the business can assign the proper items and charge each client the proper amount.

 

A third method of customization on a client-by-client basis is marketing to specific audiences. Companies often track the pages people visit so they can display advertisements based on a person’s browsing trends. Many people consider tracking to be an invasion of their privacy, an increasingly sensitive issue in our information-based society. See Chapter 32 for more information on this and other legal, ethical and moral issues.

 

The server performs session tracking by keeping track of when a specific person visits a site. The first time a client connects to the server, the server assigns the user a unique ses-sion ID. When the client makes additional requests, the client’s session ID is compared with the session IDs stored in the server’s memory. Active Server Pages use the Session object to manage sessions. The Session object’s Timeout property specifies the number of minutes that a session exists before it expires. The default value for property Timeout is 20 minutes. Calling Session method Abandon can also terminate an indi-vidual session.

 

 

    <hr />5/24/2001 <a href = "mailto:tem@deitel.com">tem</a>: ASP is a great tool for server-side development.

 

<hr />5/24/2001 <a href = "mailto:dan@bushycat.com">dan</a>: ASP is my preferred server-side development tool.

 

 

Figure 25.15 is an ASP page generator. Users who are not familiar with ASP may input their information in a form and submit the form, and the ASP page generator will create the user’s ASP page. This example consists of two Active Server Pages linked to each other through HTTP post requests. We use session variables in this example to maintain a state between the two ASP pages. Multiple Active Server Pages connected in this manner are sometimes called an ASP application. The first page, instantpage.asp (Fig. 25.15), consists of a form that requests information from the user. When submitted, the form is posted to process.asp (Fig. 25.18). If there are no errors, process.asp creates the user’s ASP page. Otherwise, process.asp redirects the user back to instantpage.asp. Also, process.asp stores a “welcome back” message in session variable welcomeBack. Each time a user submits the form, process.asp stores a new “welcome back” message in the session variable. If a file name is not provided, pro-cess.asp returns an error to instantpage.asp (Fig. 25.15). [Note: The example presented is IIS specific. PWS users should use the version in the PWS folder in the Chapter 25 examples directory (on the CD-ROM that accompanies this book). Separate files are included on the CD for users running Personal Web Server.

 

Line 30 is a server-side include (SSI) statement that incorporates the contents of header.shtml (Fig. 25.16) into the ASP file. Server-side includes are commands embedded in XHTML documents that add dynamic content. The SSI statement in line 30 is replaced with the contents of the file header.shtml. The word virtual in the SSI refers to the include file’s path as it appears below the server’s root directory. This is often referred to as a virtual path. SSIs can use file instead of virtual to indicate a physical path relative to the directory of the current file on the server. For example, line 30 could be rewritten as

<!-- #include file = "includes\header.shtml"-->

 

which assumes that header.shtml is in the includes folder under the directory that contains instantpage.asp on the server.

 

Not all Web servers support the available SSI commands. Therefore, SSI commands are written as XHTML comments. SSI statements always execute before any scripting code executes.

 

 

          <% @LANGUAGE = VBScript %>

 

 

          <%

          ' Fig. 25.15 : instantpage.asp

          ' ASP document that posts data to process.asp

          Option Explicit

          %>

 

          <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

          "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 

          <html xmlns = "http://www.w3.org/1999/xhtml">

 

          <head>

          <title>Instant Page Content Builder</title>

         

          <style type = "text/css">        

          table { text-align: center;        

          font-size: 12pt;    

          color: blue; 

          font-size: 12pt;    

          font-family: arial, sans-serif } 

          </style>     

                  

          </head>     

                  

          <body>      

                  

          <!-- include the header   -->

          <!-- #include virtual = "/includes/header.shtml" -->

          <h2>Instant Page Content Builder</h2>

 

          <% ' if process.asp posted an error, print the error

          ' message.

          If Session( "errormessage" ) <> "no error" Then

          Call Response.Write( Session( "errorMessage" ) )

          ' otherwise, print the welcome back message, if any

          Else

          Call Response.Write( Session( "welcomeBack" ) )

          End If

 

          %>

          <!-- a form to get the information from the user -->

          <form action = "process.asp" method = "post">

          <table>

          <tr>

          <td>Your Name:  </td>

         

          <td><input type = "text" size = "60"

          name = "username" /></td>

          </tr>

         

          <tr>

          <td>Enter the Filename:</td>

         

          <td><input type = "text" size = "60"

          name = "filename"

          value = "yourfilename" /></td>

          </tr>

         

          <tr>

          <td>Enter the Title:</td>

         

          <td><input type = "text" size = "60"

          name = "doctitle"

          value = "document title" /></td>

          </tr> 

                  

          <tr>  

          <td>Enter the content:</td>   

                  

          <td><textarea name = "content" rows = "3"

          cols = "50">        

          Replace this text with the

          information you would like to post.</textarea></td>

          </tr>

          </table>

         

          <input type = "submit" value = "submit" />

          <input type = "reset" value = "clear" />

          </form>

 

          <!-- #include virtual = "/includes/footer.shtml" -->

          </body>

          </html>




 

Fig. 25.15  ASP that posts user information to process.asp

 

          <!-- Fig. 25.16: header.shtml   -->

 

          <!-- Server-side include file containing XHTML -->

          <hr style = "color: blue" />

          <img height = "100" src = "/images/bug2bug.gif" alt = "Bug" />

          <hr style = "color: blue" />

Fig. 25.16  File listing for header.shtml.

 

We also use an SSI in line 83 to include footer.shtml (Fig. 25.17).

Session variable errorMessage is used in this example for error messages, and ses-sion variable welcomeBack is used to display a “welcome back” message to a returning user. The If statement on lines 35–40 tests if the value of session variable errorMes-sage is not equal to "no error." If True, the value of session variable errorMes-sage is written to the client in line 36. Otherwise, welcomeBack’s value is written to the client. When the user first requests instantpage.asp, session variable errorMessage does not have a value, and line 35 returns True. A session variable that has not explicitly been given a value contains an empty string. Although line 36 is executed, session variable errorMessage has no value, and thus line 36 does not print anything to the client. Note that Session( "errorMessage" ) never contains a value unless process.asp encounters an error and transfers the user back to instantpage.asp. A session variable’s value is set and retrieved using the Session object.

 

Line 44 requests Active Server Page process.asp when the form is posted. The remainder of instantpage.asp is XHTML that defines the form input items and the page footer.

 

          <!-- Fig. 25.17: footer.shtml    -->

          <!-- Server-side include file containing XHTML -->

    <hr style = "color: blue" />

    <a style = "text-align: center"

    href = "mailto:orders">ordering information</a> -

    <a style = "text-align: center"

    href = "mailto:editor">contact the editor</a><br />

<hr style = "color: blue" />

 

Fig. 25.17  File listing for footer.shtml.

 

 

The document process.asp (Fig. 25.18) creates the user’s ASP document and pre-sents a link to the user’s page. This page (process.asp) is requested by

instantpage.asp (line 44).

 

 

          <% @LANGUAGE = VBScript %>

 

 

          <%

          ' Fig. 25.18 : process.asp

          ' ASP document that creates user's ASP document

          Option Explicit

          %>

 

          <%

          Dim message, q

         

          q = Chr( 34 )  ' assign quote character to q

          Session( "errorMessage" ) = "no error"

 

          ' check to make sure that they have entered a

          ' valid filename

          If ( LCase( Request( "filename" ) ) = "yourfilename" ) _

          Or Request( "filename" ) = "" Then

          message = "<p style = " & q & "color: red" & q & _

          ">" & "Please enter a valid name or filename.</p>"

          Session( "errorMessage" ) = message

          Call Server.Transfer( "instantpage.asp" )

          End If

 

          Dim directoryPath, filePath, fileObject, fileName

 

 

          ' Create a FileSystem Object

          Set fileObject = Server.CreateObject( _

          "Scripting.FileSystemObject" )

 

          directoryPath = _

          Request.ServerVariables( "APPL_PHYSICAL_PATH" )

         

          fileName = Request( "filename" ) & ".asp"

 

 

          ' build path for text file

          filePath = directoryPath & "\" & fileName

         

          ' check if the file already exists

          If fileObject.FileExists( filePath ) Then

          message = "<p style = " & q & "color: red" & q & _

          ">" & "The file name is in use.<br />" & _

          "Please use a different file name.</p>"

          Session( "errorMessage" ) = message

          Call Server.Transfer( "instantpage.asp" )

          End If

 

          ' save XHTML for the welcome back message

          ' in a session variable

          message = "<p style = " & q & "color: blue" & q & _

          ">" & "Welcome Back, " & Request( "username" ) & _

          "</p><br />"

          Session( "welcomeBack" ) = message

 

          Dim header, footer, textFile, openMark, closeMark

          openMark = "<" & "%"

          closeMark = "%" & ">"

 

          ' build the header.

          ' vbCrLf inserts a carriage return/linefeed into the text

          ' string which makes the XHTML code more readable

          header = openMark & " @LANGUAGE = VBScript " & closeMark _

          & vbCrLf & openMark & " ' " & fileName _

          & " " & closeMark & vbCrLf & vbCrLf _

          & "<!DOC" & "TYPE html PUBLIC " & q & _

          "-//W3C//DTD XHTML 1.0 Transitional//EN" & q & _

          vbCrLf & q & "http://www.w3.org/TR/xhtml1/" & _

          "DTD/xhtml1-transitional.dtd" & q & ">" & vbCrLf & _

          "<html xmlns = " & q & "http://www.w3.org/1999/xhtml" & _

          q & ">" & vbCrLf & "<head>" & vbCrLf _

          & "<meta name = " & q & "author" & q & " content = " _

          & q & Request( "username" ) & q & " />" & vbCrLf _

          & "<meta name = " & q & "pubdate" & q & " content = " _

          & q & Date() & q & " />" & vbCrLf _

          & "<title>" & Request( "doctitle" ) & "</title>" _

          & vbCrLf & "</head>" & vbCrLf & "<body>" & vbCrLf _

          & "<!-- #" & "include " & "virtual = " & _

          "/includes/header.shtml -->" _

          & vbCrLf & "<h2 style = " & q & "text-align: center" & _

          q & "><em>" & Request( "doctitle" ) & "</em></h2>" & _

          vbCrLf & "<br />" & vbCrLf

 

          ' build the footer using a different style for

          ' building the string

          footer = vbCrLf & "<br /><br /><br />" & vbCrLf & _

          "You have requested this page on " & _

          openMark & " =Date() " & closeMark & "," & _

          vbCrLf & "at " & openMark & " =Time() " & _

          closeMark & "." & vbCrLf & _

          "<!-- #" & "include " & "virtual = " & _

          "/includes/footer.shtml -->" _

          & vbCrLf & vbCrLf & "</body>" & vbCrLf & "</html>"

         

          ' create the ASP file

          Set textFile = fileObject.CreateTextFile( filePath, False )

          With textFile

          Call .WriteLine( header & Request( "content" ) & _

          footer )

          Call .Close()

          End With

          %>

 

          <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

          "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

         

          <html xmlns = "http://www.w3.org/1999/xhtml">

 

          <head>

          <!-- use the title given by the user -->

          <title>File Generated: <% =fileName %></title>

         

          <style type = "text/css">

          h2 { font-family: arial, sans-serif;

          text-align: center }

          </style>

         

          </head>

         

          <body>

          <!-- #include virtual = "/includes/header.shtml" -->

          <h2><em>File <% =fileName %>

          was created successfully.</em>

          </h2><br />

 

          <!-- provide a link to the generated page -->

          <a href = "<% =fileName %>">View your file</a>

          <!-- #include virtual = "/includes/footer.shtml" -->

          </body>

          </html>

Fig. 25.18  ASP document that dynamically generates an ASP document

 

The If statement in line 17–18 validates the contents of field Enter the Filename. If the field is empty or contains the default string yourfilename, lines 19–21 assign XHTML text containing an error message to the variable message. Line 21 assigns the value of variable message to session variable errorMessage.

 

Then, line 22 calls Server method Transfer to request instantpage.asp. Session variable errorMessage is accessible by this ASP page.

 

If the user has entered a valid file name, an FSO object is created in lines 28–29 and assigned to reference fileObject.

 

Lines 31–32 specify the path on the server where the ASP file eventually will be written. We call Request method ServerVariables to retrieve the physical path. Line 34 builds the file name by concatenating the file name specified by the user to the

 

.asp file extension. Similarly, line 37 builds the file path by concatenating the file name to the directory path and assigns this value to variable filePath.

 

This filePath is passed to FSO method FileExists—which is called in line 40 to determine if the file exists. If it does exist, another user has already created an ASP doc ument with the same file name. If this is the case, XHTML containing an error message is set as the value of session variable errorMessage. Line 45 calls Server method

Transfer to request instantpage.asp.

 

Lines 50–53 assign XHTML for the “welcome back” message to session variable welcomeBack. The format of the message is

 

Welcome back, X!

 

where X is the current user’s name obtained from the form’s username field.

Lines 56–57 assign the ASP scripting delimiters to string variables openMark and closeMark. We use two strings instead of one to represent the opening and closing delimiters (i.e., "<" & "%") because the interpreter treats the single string "<%" as a scripting delimiter.

 

Next, we build the user’s ASP file. For clarity, we divide the file into three parts: a header, a footer and the content (provided by the user in the form’s content field).

 

Lines 62–81 construct XHTML for the header and assign it to variable header. VBScript constant vbCrLf is used to insert a carriage-return line-feed combination. The form’s values are retrieved using the Request object. Lines 85–92 create the page’s footer and assign it to variable footer.

 

Lines 95–100 write header, text area content’s text and footer to the text file before closing it. Lines 103–129 send XHTML to the client that contains a link to the cre-ated page. Figure 25.19 is a sample ASP file—named test.asp—created by Active Server Page process.asp. [Note: We added lines 1–2 for presentation purposes.]. The screen capture in Fig. 25.20 shows the message displayed when the user returns back to instantpage.asp. The screen capture (Fig. 25.21) shows the error message generated when the user does not change the default file name in the Enter the Filename field.

Another popular way to customize Web pages is via cookies. Cookies store informa-tion on the client’s computer for retrieval later in the same browsing session or in future browsing sessions. For example, cookies could be used in a shopping application to keep track of the client’s shopping-cart items.

 

          <% @LANGUAGE = VBScript %>

          <% ' test.asp %>

 

          <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

          "http://www.w3c.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

          <html xmlns = "http://www.w3.org/1999/xhtml">

          <head>

          <meta name = "author" content = "tem" />

          <meta name = "pubdate" content = "2/27/2001" />

          <title>XML How to Program</title>

          </head>

          <body>

          <!-- Fig. 25.16: header.shtml   -->

          <!-- Server-side include file containing XHTML -->

          <hr style = "color: blue" />

          <img height = "100" src = "/images/bug2bug.gif" alt = "Bug" />

          <hr style = "color: blue" />

          <h2 style = "text-align: center"><em>XML How to Program</em></h2>

          <br />

 

          The authoritative Deitel&#8482; Live-Code&#8482;

          introduction to XML-based systems development.

          ISBN 0-13-028417-3

 

          <br /><br /><br />

          You have requested this page on 2/27/2001,

          at 10:14:44 PM.

          <!-- Fig. 25.17: footer.shtml    -->

          <!-- Server-side include file containing XHTML -->

          <hr style = "color: blue" />

          <a style = "text-align: center"

          href = "mailto:orders">ordering information</a> -

          <a style = "text-align: center"

          href = "mailto:editor">contact the editor</a><br />

          <hr style = "color: blue" />

 

          </body>

          </html>

Fig. 25.19  XHTML document generated by process.asp

 

Cookies are small files sent by an Active Server Page (or another similar technology, such as Perl—discussed in Chapter 27) as part of a response to a client. Every HTTP-based interaction between a client and a server includes a header that contains information about either the request (when the communication is from the client to the server) or the response (when the communication is from the server to the client). When an Active Server Page receives a request, the header includes the request type (e.g., get or post) and cookies stored on the client machine by the server. When the server formulates its response, the header information includes any cookies the server wants to store on the client computer.

 

Depending on the maximum age of a cookie, the Web browser either maintains the cookie for the duration of the browsing session (i.e., until the user closes the Web browser) or stores the cookie on the client computer for future use. When the browser makes a request to a server, cookies previously sent to the client by that server are returned to the server (if the cookies have not expired) as part of the request formulated by the browser. Cookies are automatically deleted when they expire (i.e., reach their maximum age). We use cookies in Section 25.8 to store user IDs.

 

Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail


Copyright © 2018-2020 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.