1. Trang chủ
  2. » Công Nghệ Thông Tin

Teach Yourself E-Commerce Programming with ASP in 21 Days phần 2 ppsx

62 237 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Using Application and Session Objects in E-Commerce Applications
Trường học University of Example
Chuyên ngành E-Commerce Programming
Thể loại Bài viết
Năm xuất bản 2025
Thành phố Example City
Định dạng
Số trang 62
Dung lượng 391,15 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

For example, assume that Ruth visits your Web site and retrieves a page whichassigns the value blueto the Sessionvariable named favoriteColor.. Now assume thatAndrew visits your Web site

Trang 2

program-The ability to track customers and personalize content is important because youcan use it to increase sales To take a simple example, you might want to dis-play different advertisements to different customers depending on their inter-ests If you have recorded the fact that a certain customer likes looking at pages

in your Web site related to fishing rods, you can automatically show this tomer more advertisements related to fishing rods

cus-Today, you will learn the following:

• How to add cookies to customers’ browsers so that you can automaticallyidentify customers whenever they return to your Web site

Trang 3

• How to use Sessionand Applicationvariables to store persistent information.

• How to use the Global.asa file to detect when customers first arrive at your Website and when they leave

Tracking Customers with Cookies

Cookies have gotten a lot of media attention lately because of fears that they pose athreat to people’s privacy You can use a cookie to store information on a customer’scomputer when the customer visits your Web site You can then use this information toidentify the customer once again whenever the customer returns to your Web site.Cookies were developed by Netscape to fix a perceived deficit in the way that Webservers and Web browsers interact Without cookies, the interaction between Web serversand browsers is stateless You cannot identify the same user of your Web site as the usermoves from page to page

Where did the term “cookie” come from? Lou Montulli, the person who wrote the original cookie specification for Netscape, explains “A cookie is a well-known computer science term that is used when describing an opaque piece of data held by an intermediary The term fits the usage precisely; it’s just not a well-known term outside of computer science circles.”

Note

The stateless nature of Web server and browser interaction creates a number of problemsfor Web site developers For example, imagine you have created a special area of yourWeb site that contains content which only registered members can view Without usingcookies, it is difficult to track whether a particular user is a registered member If theuser logs in on one page, it is difficult to detect whether it is the same user on anotherpage

A good source of information on cookies is the Cookie Central Web site located at http://www.cookiecentral.com

Note

There are two types of cookies: session cookies and persistent cookies Session cookiesare stored in memory They last on a customer’s computer only while the customer is vis-iting your Web site

Trang 4

A persistent cookie, on the other hand, can last many months or even years Persistentcookies are stored in a text file on the customer’s computer This text file is called theCookie file on Windows computers and the Magic Cookie file on Macintosh computers

Netscape Navigator and Internet Explorer store persistent cookies a little differently

Netscape stores all the cookies from every Web site in one file named “Cookies.txt” Youcan find this file under the /Netscape or /Netscape/User/Username folder For example,here are the contents of the Netscape Navigator cookie file on my computer:

# Netscape HTTP Cookie File

# http://www.netscape.com/newsref/std/cookie_spec.html

# This is a generated file! Do not edit.

.superexpert.com TRUE / FALSE 965026643 u steve superexpert.com TRUE / FALSE 965026643 p secret www.webtrends.com FALSE / FALSE 1293753685 WEBTRENDS 4MNFP9Z98A flycast.com TRUE / FALSE 1293753600 atf 1_4880095465

.doubleclick.net TRUE / FALSE 1920499052 id d6685383

As you can see, my cookie file contains five cookies The first two cookies were created

by the superexpert Web site The first cookie is named “u”(which stands for username)and has the value “steve” The second cookie is named “p”(which stands for password)and it contains my secret password at superexpert (well, not really) My cookie file alsocontains cookies added by Webtrends (a company that produces a popular log analysistool for Internet Information Server) and the two advertising networks Flycast andDoubleClick

Microsoft Internet Explorer creates a separate cookie file for each Web site All thesefiles are located in the /Windows/Cookies folder For example, on my computer, I have acookies file named “administrator@amazon.txt” that was created by the Amazon Website

It is important to understand that a Web site can read only the cookies it has set Forexample, if you visit both the Amazon and superexpert Web sites, and both sites add acookie to your computer, Amazon can read only its own cookies and not any cookies set

by superexpert So, if you add a cookie to a customer’s computer, only you or the tomer can view the contents of the cookie

Trang 5

cus-It is also important to understand that not all browsers support cookies There are a ber of reasons why a browser might not support cookies First, some people dislike cook-ies because of privacy worries, and they have disabled cookies on their browser Second,cookie files have a tendency to become corrupted for one reason or another Finally, eventhough cookies have been around since Netscape Navigator 1.0, for some mysterious rea-son, there are still some browsers that do not support cookies.

num-You should never assume that a customer has cookies enabled on their browser Forexample, a perfectly legitimate use of cookies is to automatically log in a user at yourWeb site If you do this, however, you should include a way for users who do not havecookies enabled to log in

Adding a Cookie to a Customer’s Browser

You can add a cookie to a customer’s browser by using the Cookiescollection of theResponseobject For example, imagine that you want to add a cookie namedcustomerNamethat contains a customer name To add this cookie, you would use the fol-lowing statement:

Response.Cookies( “customerName” ) = “Ruth Johnson”

This statement adds a cookie named “customerName”that has the value “Ruth Johnson” The cookie that is created is a session cookie It last only while the customer

is visiting your Web site

To create a persistent cookie, you must include the date when the cookie will expire You

do this by using the Expiresattribute of the Cookiescollection For example, the lowing two statements create a cookie that will last until July 4, 2002:

fol-Response.Cookies( “customerName” ) = “Ruth Johnson”

Response.Cookies( “customerName” ).Expires = “July 4, 2002”

When creating cookies, you must create the cookie before any content is sent to thebrowser Otherwise you will receive the following error:

Advertising networks, like Flycast and DoubleClick are able to work around the rule that a cookie can only be read by the Web site that creates it They use a trick When a Web site displays a banner advertisement from one of these networks, the advertisement is actually retrieved from the advertising network’s servers Therefore, an advertising network can set and read a cookie from any Web site that displays its advertisements This means that advertising networks can track users as they move from Web site to Web site.

Note

Trang 6

Header Error The HTTP headers are already written to the client browser Any HTTP header modifications must be made before writing page content.

If you want to get around this limitation, you can buffer your ASP page When youbuffer an ASP page, the page is not sent immediately to a browser It is retained in mem-ory until the whole page is processed To buffer an ASP page, include the followingstatement at the top of the page:

<% Response.Buffer = TRUE %>

Internet Information Server 5.0 buffers all pages by default However, the Personal Web Server and versions of Internet Information Server before version 5.0, do not buffer page content unless the property is explicitly enabled.

Note

You can place any content that you please in a cookie However, you should be aware ofsome of the limitations of cookies According to the original cookie specification (seehttp://home.netscape.com/newsref/std/cookie_spec.html), a single computer canhold a maximum of 300 cookies from all Web sites Furthermore, a single Web site can-not add more than 20 cookies to a customer’s computer Finally, an individual cookie canhold no more than 4KB of data This limit applies to a combination of the size of thecookie’s name and the size of the data contained in the cookie

Reading Cookies from a Customer’s Browser

You can read a cookie you have placed on a customer’s computer by using the Cookiescollection of the Requestobject For example, to retrieve a cookie named usernameandassign it to a local variable named username, you would use the following statement:

username = Request.Cookies( “username” )Because the Cookiescollection is a collection of the Requestobject, you can also justuse:

username = Request( “username” )However, if there is a query string variable or form variable named username, using theprevious statement would return the value of the query string or form variable instead ofthe cookie variable When you don’t explicitly specify a collection using the Requestobject, the collections are searched in the following order:

Trang 7

L ISTING 3.1 Displaying All Cookies

6 FOR EACH cookie IN Request.Cookies

7 Response.Write cookie & “=” & Request.Cookies( cookie ) & “<BR>”

You can use Sessionvariables as another method of tracking customer information as acustomer moves from page to page on your Web site Sessionvariables are closely relat-

ed to cookies In fact,Sessionvariables rely on cookies

When you use either the Personal Web Server or Microsoft Internet Information Server,the Web server automatically adds a special cookie to every visitor’s browser This cook-

ie is called the ASPSessionIDcookie (when it’s added to a customer’s computer, extrarandomly generated characters are added to the name of the cookie for security reasons).The Web server uses the ASPSessionIDcookie to associate Sessionvariables with a par-ticular user Sessionvariables are stored in the memory of the Web server You can use aSessionvariable to store any type of information including text, numbers, arrays andeven ActiveX components

A NALYSIS

Trang 8

Before you use Sessionvariables, however, you should be warned that they have some

of the same drawbacks as cookies If a customer is using a browser that doesn’t supportcookies, the Web server cannot create the ASPSessionIDcookie Without the

ASPSessionIDcookie,Sessionvariables cannot be associated with a customer as thecustomer moves between pages So, it is a good idea to avoid using Session variableswhenever possible

Using Session variables in your ASP application can also make your tion less scalable Each Session variable uses server memory Furthermore, using Session variables makes it more difficult to use multiple Web servers for a Web site (a Web farm) because Session variables are created on an individual server.

is sent to the browser

After the favoriteColor Sessionvariable has been created and assigned a value, it willretain that value throughout the time that a user visits your Web site The favoriteColor Sessionvariable will be associated with a particular user by using the ASPSessionIDcookie

To retrieve a Sessionvariable after it has been created, you also use the Sessionobject

The ASP page in Listing 3.3 displays the value of the favoriteColor Sessionvariablecreated in Listing 3.2

A NALYSIS

Trang 9

L ISTING 3.3 Displaying a Session Variable

It is important to understand that Sessionvariables are created relative to particularusers For example, assume that Ruth visits your Web site and retrieves a page whichassigns the value blueto the Sessionvariable named favoriteColor Now assume thatAndrew visits your Web site and retrieves a page which assigns the value redto aSessionvariable named favoriteColor After Andrew retrieves his page, the value offavoriteColordoesn’t change for Ruth Each visitor has his own unique set of Sessionvariables assigned to him

Sessionvariables persist until a user leaves your Web site How does the Web serverdetect when this happens? By default, the Web server assumes that if a user doesn’trequest a page for more than 20 minutes, the user has left You can change this defaultbehavior with the Timeout property of the Sessionobject

For example, if you have a Web site that includes long product descriptions which aretime-consuming to read, you might want to change the Timeout property to 60 minutes.You can do this by adding the following statement at the top of a page:

Session.Timeout = 60You specify the value of the Timeout property in minutes The new value of Timeout willapply to the user throughout the remainder of her user session

Storing Arrays in Session Variables

One common use for Sessionvariables is for storing a customer’s shopping cart Youcan create a shopping cart by assigning an array to the Sessionvariable The elements inthe array represent each of the products a customer has added to his shopping cart.The script in Listing 3.4 illustrates how you can create an array, assign values to two ofits elements, and then create a Sessionvariable that contains the array

A NALYSIS

Trang 10

After an array has been assigned to a Sessionvariable, you can display any element ofthe array by referring to its index For example, the following statement displays the ele-ment of the Session array with an index of 1.

Response.Write Session( “ShoppingCart” )( 1 )

If the Session array were created with the script in Listing 3.4, the previous statementwould display the value “comb”

However, you cannot change the value of an element in a Session array directly Tochange any of the values in a Session array, you must first assign the Session array to anormal VBScript array, make the change, and then assign the array to the Sessionvari-able once again

For example, the script in Listing 3.5 demonstrates how to change the value of the ond element of the ShoppingCart Session array from combto toothbrush

sec-L ISTING 3.5 Changing the Value of a Session Array

Session( “ShoppingCart” )( 1 ) = “toothbrush”

This statement won’t generate an error However, it will have absolutely no effect Youcannot change a value of a Session array directly.ble once again

A NALYSIS

Trang 11

Tracking a Session with a SessionID

TheSessionobject has a valuable property for uniquely identifying users: theSessionIDproperty Each visitor to your Web site is automatically assigned a uniquenumber You can retrieve that unique number with the SessionIDproperty

For example, the ASP page in Listing 3.6 displays the value of SessionIDfor the personwho requests the page

L ISTING 3.6 Displaying the SessionID Property

Ending a User Session

By default, a user session ends after the user hasn’t requested a page from your Web sitefor more than 20 minutes However, you can force a session to end earlier than this bycalling the Abandonmethod of the Sessionobject Calling the Abandonmethod removesall the Sessionvariables associated with the user who requested the page from memory.After you call the Abandonmethod, the user’s session doesn’t actually end until the cur-rent page is completely processed This means that all the user’s Sessionvariables retaintheir values until the page finishes processing Furthermore, the user’s SessionIDretainsits value throughout the page

For example, consider the ASP page in Listing 3.7

L ISTING 3.7 Calling the Abandon Method

Trang 12

The ASP page in Listing 3.7 will display “Hello World!”twice Even though theAbandonmethod is called before the Sessionvariable is displayed in line 12, the variablewill retain its value The Abandonmethod will not cause the Sessionto end until thewhole page finishes processing.

The Abandonmethod is most often used when creating a Logoff page in a Web site Forexample, you can store a customer’s username and password in Sessionvariables toidentify the customer on every page When the customer is ready to leave your Web site,she can link to a page that calls the Abandonmethod to end her user session and removeher username and password from memory

LikeSessionvariables,Applicationvariables can be used to store information overmultiple pages Unlike Sessionvariables, however,Applicationvariables aren’t associ-ated with a particular user The values stored in an Applicationvariable can be assignedand retrieved by every user of your Web site

To create an Applicationvariable, you use the Applicationobject For example, to ate an Applicationvariable named “myVar”, you would use the following statement:

cre-Application( “myVar” ) = “Hello World”

To retrieve an Applicationvariable, you also use the Applicationobject The followingstatement displays the contents of the Applicationvariable named “myVar”:

Response.Write Application( “myVar” )When the value of an Applicationvariable is changed, it is changed for every user of yourWeb site For example, imagine that Ruth retrieves a page from your Web site which assigns

A NALYSIS

Trang 13

the value blueto the Applicationvariable named favoriteColor Now, suppose thatAndrew comes along and retrieves a page that assigns the value redto the Applicationvariable favoriteColor After Andrew changes the value of the favoriteColor Applicationvariable, the value of this variable will be changed for everyone After Andrewretrieves the page, the favoriteColorvariable also has the value redfor Ruth.

Because the same Applicationvariable can be changed by different users of your Website, conflicts can occur For example, a common use of Applicationvariables is fortracking the number of times a page has been viewed The ASP page in Listing 3.8 dis-plays a simple page counter (see Figure 3.1)

L ISTING 3.8 Simple Page Counter

8 This page has been viewed

9 <%=Application( “counter” )%> times.

Trang 14

The ASP page in Listing 3.8 uses an Applicationvariable named “counter”

to keep track of the number of times that the page has been viewed TheApplicationvariable is incremented in line 2 The current value of the Applicationvariable is displayed in line 9

There is an important problem with the ASP page contained in Listing 3.8 Imagine thattwo people request the page at the same time Ruth requests the page and the counterApplicationvariable has the value 345 At the same time, Andrew requests the page,and the application variable has the value 345 After both visitors retrieve the page, theApplicationvariable will have the value 346 However, because two people haverequested the page, it should have the value 347

Fortunately, there is an easy way to fix this problem The Applicationobject has twomethods named Lockand Unlock The Lockmethod locks all the Applicationvariablesand prevents anyone except the current user from reading or modifying them TheUnlockmethod releases the Applicationvariables once again

The ASP page in Listing 3.9 contains an improved version of the page counter

L ISTING 3.9 Better Page Counter

10 This page has been viewed

11 <%=Application( “counter” )%> times.

3, the Unlockmethod is called in line 4 to release the Applicationvariables

It is important to understand that calling the Lockmethod locks all the Applicationables in memory You cannot selectively lock Applicationvariables

vari-A NALYSIS

A NALYSIS

Trang 15

After you call the Lockmethod, all Applicationvariables will continue to be lockeduntil either the Unlockmethod is called or the page finishes processing This means thatyou cannot accidentally lock all Applicationvariables forever within an ASP script.You should also be aware that locking Applicationvariables doesn’t prevent other usersfrom modifying an Applicationvariable If a number of users attempt to modify anApplicationvariable at the same time, and each user requests a page that calls the Lockmethod, all the modifications will happen However, the modifications will take placeserially rather than concurrently.

Storing Arrays in Application Variables

One common use of Applicationvariables is to store frequently accessed but quently modified database records in memory Retrieving database records can be a slowprocess If the records do not change often, I recommend that you retrieve the databaserecords only once and store them in an Application array This way, the records can beretrieved very quickly from the Application array the next time they are requested

infre-You’ll learn how to retrieve database records in the lesson on Day 5,

“Building Your Product Catalog.”

3 myArray( 0 ) = “Hello World!”

4 Application( “myArray” ) = myArray

5 %>

The script in Listing 3.10 creates an array named myArrayand assigns it to anApplicationvariable named myArray The array is created in line 2 Next, avalue is assigned to an element of the array in line 3 Finally, in line 4, the local array isassigned to an Applicationvariable

You can retrieve and display a value from an Application array directly For example, thefollowing statement displays the value of the element of the Application array with anindex of 0:

Response.Write Application( “myArray” )( 0 )

A NALYSIS

Trang 16

Although you can directly read the value of an element contained in an Applicationarray, you can’t modify it For example, the following statement will have no effect:

Application( “myArray” )(2) = “Goodbye!”

If you want to change the value of an element in an Application array, you must firstassign the Application array to a local array For example, the script in Listing 3.11 prop-erly changes the value of an element contained in an Application array

L ISTING 3.11 Modifying an Element in an Application Array

1 <%

2 Application.Lock

3 myArray = Application( “myArray” )

4 myArray( 0 ) = “Goodbye!”

5 Application( “myArray” ) = myArray

6 Application( “myArray” ).Unlock

7 %>

The script in Listing 3.11 modifies an element of an Application array In line 3,the Application array named myArrayis assigned to a local array with the samename Next, in line 4, an element of the local array is modified Finally, in line 5, thelocal array is assigned to the Application array once again

Removing Application Variables From Memory

You should be careful when creating Applicationvariables Applicationvariables take

up memory Unlike a Sessionvariable, an Applicationvariable is never automaticallyremoved from memory

Prior to the version of Active Server Pages included with Windows 2000, there was noway to remove an Applicationvariable from memory using an ASP script Applicationvariables remained in memory until the Web service was stopped, the Global.asa file wasmodified, or your ASP Application was unloaded

The new version of Active Server Pages included with Windows 2000 includes two newmethods you can use to remove Applicationvariables from memory: the Remove()andthe RemoveAll()methods The Remove()method removes a particular Applicationvari-able from memory The RemoveAll()method removes all Applicationvariables frommemory

For example, the script in Listing 3.12 creates two Applicationvariables and thenremoves one of them

A NALYSIS

Trang 17

L ISTING 3.12 Using the Remove() Method

1 <%

2 Application( “myvar1” ) = “Red”

3 Application( “myvar2” ) = “Blue”

2 Application( “myvar1” ) = “Red”

3 Application( “myvar2” ) = “Blue”

4 Application.Contents.RemoveAll()

5 %>

In lines 2 and 3, two Applicationvariables are created When the RemoveAll()method is called in line 4, all Applicationvariables are removed from memoryincluding the two Applicationvariables created in this script

Using the Global.asa File

In this section, you’ll learn how to use a special file named the Global.asa file TheGlobal.asa file can contain ASP scripts However, unlike a normal ASP page, theGlobal.asa file isn’t used to display content Instead, the Global.asa file is used to handleglobal application events

Before you can use the Global.asa file, you must first create an ASP application To dothis with the Personal Web Server, follow these steps:

1 Launch the Personal Web Manager

2 Click the button labeled Advanced

3 Select your home directory and click Edit Properties

4 Check the box labeled Execute

5 Reboot your computer

To create an ASP application with Internet Information Server, follow these steps:

A NALYSIS

A NALYSIS

Trang 18

1 Launch the Internet Service Manager

2 Right-click on your Default Web Site and click properties This opens a propertysheet

3 Select the tab labeled Home Directory

4 In the section labeled Application Settings, click the button labeled Create (If youonly see a button labeled Remove, the application has already been created)

After you create an ASP application, you can add the Global.asa file to the root directory

of your application Typically, you add the Global.asa file to the wwwroot directory Youcan create the Global.asa file with a text editor just like a normal ASP page

Within the Global.asa file, you can place subroutines that are triggered by four types ofevents Here is a list of these events:

• The Session_OnStartEvent—This event is triggered when a customer first arrives

at your Web site This event occurs immediately after a customer requests the firstpage

• The Session_OnEndEvent—This event is triggered when a user session ends Thisevent occurs when a user session times out or when the Abandon()method of theSessionobject is called

• The Application_OnStartEvent—This event is triggered when the first page isretrieved from your Web site after your Web server has been started This eventalways occurs before the Session_OnStartevent

• The Application_OnEndEvent—This event is triggered when the server shutsdown It always occurs after any Session_OnEndevent

For example, suppose that you want to display a count of the current visitors at yourstore on the homepage of your store You can do this by using the Session_OnStart, theSession_OnEnd, and the Application_OnStartevents (see Listing 3.14)

L ISTING 3.14 Counting Customers

1 <SCRIPT LANGUAGE=”VBScript” RUNAT=”Server”>

9 Sub Session_OnEnd

continues

Trang 19

10 Application.Lock

11 Application( “customerCount” ) = Application( “customerCount” ) - 1

12 Application.UnLock

13 End Sub 14

15 Sub Application_OnStart

16 Application( “customerCount” ) = 0

17 End Sub 18

19 Sub Application_OnEnd

20 End Sub 21

22 </SCRIPT>

The Global.asa file contained in Listing 3.14 uses three events Lines 3–7 contain

a subroutine that handles the Session_OnStartevent Whenever a new customerarrives at your Web site, this subroutine increments the current count of customers by 1.Lines 9–13 contain a subroutine that handles the Session_OnEndevent When a customersession ends, the current customer count is decremented by 1 Finally, in lines 15–20, theApplication_OnStartevent is used to initialize the customerCountvariable

You should notice that the script delimiters <%and %>are not used in the Global.asa file.Instead, the beginning and end of the script is marked with the HTML <SCRIPT>tag (seelines 1 and 22) The RUNATattribute of the <SCRIPT>tag is given the value SERVERtoindicate that this is a server-side script rather than a client-side script

The Global.asa file in Listing 3.14 doesn’t display any content To show the currentcount of customers, you must display the Applicationvariable named customerCount

in a page This is illustrated in the page included in Listing 3.15

L ISTING 3.15 Displaying a Count of Customers

1 <HTML>

2 <HEAD><TITLE>Welcome</TITLE></HEAD>

3 <BODY>

4

5 Welcome to our store!

6 <p>There are currently

Trang 20

This page displays the number of active customers It simply displays the value

of the Applicationvariable named “customerCount”(see Figure 3.2)

3

You should be warned that you can’t use a number of the standard Active Server Pagesobjects within the Global.asa file In the Application_OnStartand Application_OnEndsubroutines, you can use only the Serverand Applicationobjects In the

Session_OnStartsubroutine, you can use any of the built-in ASP objects However, inthe Session_OnEndevent, you can only use the Application,Server, and Sessionobjects

A NALYSIS

F IGURE 3.2

Displaying active

customers.

Trang 21

In the third section, you learned how to use Applicationvariables You learned how tocreate a simple page counter with an Applicationvariable You also learned how towork with Application arrays.

Finally, in the last section of today’s lesson, you learned how to use the Global.asa file.You learned how to create subroutines to handle the Session_OnStart,Session_OnEnd,Application_OnStart, and Application_OnEndapplication events You also learnedhow to use the Global.asa file to display a count of the active customers at your Web site

Q&A

Q Should I use cookies or Session variables when creating my commercial Web site?

A There are many successful Web sites operating on the Internet that require users to

have cookies enabled However, from painful personal experience, I can tell youthat cookies and Sessionvariables don’t work with a surprising number ofbrowsers If you want to create a Web site that is accessible by the maximum num-ber of customers, I suggest you don’t use cookies or Sessionvariables On theother hand, if you need to develop a commercial Web site fast, using Sessionvari-ables can dramatically decrease the amount of time it takes to develop the Website

Q How can I avoid using cookies and Session variables?

A If you need to track customer information as the customer moves from page to

page at your Web site, you can use query strings and hidden form fields instead ofcookies or Sessionvariables For example, if you want to track a customer by acustomer ID number, you need to include the customer ID number within everyquery string and HTML form The following ASP page illustrates how to do this:

<%

‘ Get Customer ID cid = Request( “cid” )

<FORM method=”post” ACTION=”nextpage.asp”>

<input name=”cid” type=”hidden” value=”<%=cid%>”>

<input type=”submit” value=”Next Page”>

</FORM>

</BODY>

</HTML>

Trang 22

The previous page retrieves the customer ID from the Requestobject and passes it

to the next page in both a query string and hidden form field Notice that usingRequest( “cid” )retrieves the customer ID no matter if it is included in theQueryStringor Form collection of the Requestobject

to persist until a certain date?

2 Suppose that Andrew requests an ASP page which assigns the value redto aSessionvariable named color Now, suppose that Ruth requests an ASP pagewhich assigns the value blueto the Sessionvariable named color If Andrewrequests an ASP page that outputs the value of the color Sessionvariable, whatvalue will be displayed?

3 How can you remove all the Sessionvariables associated with a particular userfrom memory?

4 Suppose that Andrew requests an ASP page which assigns the value redto anApplicationvariable named color Now, suppose that Ruth requests an ASP pagewhich assigns the value blueto the Applicationvariable named color If Andrewrequests an ASP page that outputs the value of the color Applicationvariable,what value will be displayed?

5 What’s wrong with the following Global.asa file?

<%

Sub Session_OnStart Application.Lock Application( “customerCount” ) = Application( “customerCount” ) + 1 Application.UnLock

End Sub Sub Session_OnEnd Application.Lock Application( “customerCount” ) = Application( “customerCount” ) - 1 Application.UnLock

End Sub

Trang 23

Sub Application_OnStart Application( “customerCount” ) = 0 End Sub

%>

Exercise

Create an ASP page that lists the SessionIDand the entry time of all the customerswho have visited your Web site To do this, you will need to create a Global.asafile to detect when the customer arrives and an ASP page to display the list ofSessionIDs and entry times

Trang 24

program-• How to use the #INCLUDEdirective to include files in an ASP page such

as a standard company logo

• How to automatically redirect a customer to a new ASP page file

• How to use the File Access component to store customer information in atext file

Including Files in an ASP Page

You can include a file within an ASP page by using the server-side #INCLUDEdirective You can use the #INCLUDEdirective with both Active Server Pages andstandard HTML files

Trang 25

Including files is useful in two situations First, including files is useful when you need

to add the same content to a number of pages at your Web site

For example, imagine that you have a standard corporate logo you want to include at thetop of every page of your Web site You can place the logo in a header file and simplyinclude this file in each ASP page

Displaying the company logo with a header file makes it easier to create a consistentlook for your Web site It also makes it easier to change your pages at a future date if thecompany logo is modified Instead of changing all the pages at your Web site, you onlyneed to modify the header file

Including files is also useful when you need to use a standard set of functions and dures within multiple Active Server Pages You can create a library of functions and pro-cedures in one file and include this file in other Active Server Pages If you need a newfunction that will be used on multiple Active Server Pages, you can simply add the newfunction to the included file

proce-You include a file in an ASP page by using the server-side #INCLUDEdirective The filethat you include can be contained in any directory accessible to your Web server Thereare two forms of the directive If you want to include a file in an ASP page that is in thesame directory as the ASP page, you use the following syntax:

<! #INCLUDE FILE=”somefile.asp” >

You can also use the FILEattribute when including a file that is located in a subdirectory

of the current directory However, when using the FILEattribute, the included file mustalways be located in the current directory or a subdirectory of the current directory

If the file you want to include is located in a different directory, you must use theVIRTUALattribute rather than the FILEattribute The following #INCLUDEdirectiveincludes a file that is located in the commonfiles directory:

<! #INCLUDE VIRTUAL=”/commonfiles/somefile.asp” >

For example, the ASP page in Listing 4.1 uses the #INCLUDEdirective to include two files named standardheader.aspand standardfooter.asp The contents of the standardheader.aspfile is included in Listing 4.2 The contents of the

standardfooter.aspfile is included in Listing 4.3

L ISTING 4.1 Including a Header File

Trang 26

The ASP page in Listing 4.1 includes the file named standardheader.aspin line

1 and includes the file named standardfooter.aspin line 5 Notice that the

#INCLUDEdirective isn’t used within the ASP page script delimiters <%and %> When youuse the #INCLUDEdirective, you must add the directive outside any scripts

L ISTING 4.2 The standardheader.asp File

1 <HTML>

2 <HEAD><TITLE>Company Name</TITLE></HEAD>

3 <BODY BGCOLOR=”lightblue”>

4 <IMG SRC=”companylogo.gif” ALIGN=”CENTER”>

The standardheader.aspfile contains the standard HTML tags that appear atthe top of the page It also includes the company logo in line 4

L ISTING 4.3 The standardfooter.asp File

Tip

When including a standard header in multiple ASP pages, you often need to change tain aspects of the included file on each page For example, you might want each page todisplay a different title You can vary certain aspects of a standard header by includingvariables in the header This is illustrated in the Active Server Pages contained in Listing 4.4 and Listing 4.5

Trang 27

cer-L ISTING 4.4 Including a Header File with Variables

1 <%

2 docTitle = “Company Homepage”

3 docDesc = “The homepage of The Company”

4 docKeys = “The Company, Company, Widgets”

L ISTING 4.5 Header File with Variables

1 <HTML>

2 <HEAD>

3 <META NAME=”DESCRIPTION” CONTENT=”<%=docDesc%>”>

4 <META NAME=”KEYWORDS” CONTENT=”<%=docKeys%>”>

5 <TITLE><%=docTitle%></TITLE>

6 </HEAD>

7 <BODY BGCOLOR=”lightblue”>

8 <IMG SRC=”companylogo.gif” ALIGN=”CENTER”>

The header file in Listing 4.5 uses variables for both the <META>tags and the

<TITLE>tag In lines 3 and 4, the variables named docDescand docKeysare usedfor the contents of the <META>tags In line 5, the title of the Web page is displayed withthe docTitlevariable

A NALYSIS

A NALYSIS

Some, but not all, search engines use HTML <META> tags when indexing Web pages For example, when the AltaVista search engine lists a Web page, it uses the <META> description tag for the description of the Web page.

Note

Using the #INCLUDEdirective is also valuable when you need to include a standardlibrary of functions and subroutines in an ASP page For example, suppose that you use afunction named formatText()in multiple Active Server Pages Instead of copying andpasting the function into each ASP page, you can simply include a file that contains thefunction This is illustrated in the Active Server Pages in Listing 4.6 and 4.7

Trang 28

The ASP page in Listing 4.6 uses a function named formatText()in line 6.

Notice that the formatText()function isn’t defined in the page TheformatText()function is contained in the standardfuncs.aspfile that is included

in the ASP page

L ISTING 4.7 The standardfuncs.asp File

1 <%

2 FUNCTION formatText( theText )

3 theText = UCASE( theText )

4 theText = “<H2>” & theText & “</H2>”

Dynamically Including Files

When using include files, you might be tempted to dynamically include different filesdepending on the value of a variable For example, the ASP page contained in Listing 4.8attempts to use the #INCLUDEdirective to display one or another of two HTML pagesdepending on the value of a variable named showPage

L ISTING 4.8 Improper Dynamic Include

Trang 29

Regrettably, however, the ASP page in Listing 4.8 won’t work as intended The problem

is that all server-side directives, including the #INCLUDEdirective—are processed beforethe scripts in a page are processed This means the #INCLUDEdirective in Listing 4.8 willattempt to include a file named <%=showPage%> Most likely, this is not what you want

If you need to dynamically include different files depending on the value of a variable,you must use either a VBScript conditional or a VBScript SELECT CASEstatement Forexample, the script in Listing 4.9 will correctly display different files depending on thevalue of the variable named showPage

L ISTING 4.9 Proper Dynamic Include

1 <%

2 showPage = Request( “showpage” )

3 SELECT CASE showPage

It is important to understand that the different pages in the script in Listing 4.9 are notconditionally included Because the #INCLUDEdirective is interpreted before any scriptsare executed, all the pages are merged together into one big file before the

SELECT CASEstatement is interpreted

Including too many files and creating a very large Active Server Page can create lems The problems arise when the first user requests the page It might take a long timefor your Web server to build the file As long as the page isn’t altered or your Web serverisn’t shut down, subsequent requests should be satisfied much faster because the Webserver will cache the page

prob-A NALYSIS

Trang 30

Using File Redirection

The Requestobject includes a method that can be used to automatically redirect a tomer to a new file I’m going to explain how to use this method in this section Youshould know about it; many programmers use it However, I will also suggest that younever use this method on your own Web site

cus-You can automatically redirect a customer to a new page by using the Redirectmethod

of the Responseobject For example, the script in Listing 4.10 will automatically transfer

a customer to a page named login.aspif the customer’s username and password cannot

be retrieved from the Requestobject

L ISTING 4.10 Using Browser Redirection

1 <%

2 username = TRIM( Request( “username” ) )

3 password = TRIM( Request( “password” ) )

4 IF username = “” OR password = “” THEN

The Redirectmethod uses browser redirection If a customer requests the page inListing 4.10, and the customer hasn’t logged in, the server sends a message to the brows-

er telling the browser to request the login.asppage So, the browser must request twopages before the login.asppage is shown

You can pass query string variables with the Redirectmethod However, you cannot usethe TARGETattribute This means that you cannot redirect a customer to a particular win-dow or frame

Finally, not all browsers fully support the Redirectmethod If a customer is using abrowser that doesn’t support redirects, a page displaying a message similar to the follow-ing message will be displayed in the customer’s browser:

302: Object has Moved

A NALYSIS

Trang 31

I recommend that you never use browser redirects when building your Web site for tworeasons First, using redirects places more strain on your Web server because it forces thebrowser to retrieve two pages instead of one Second, redirects aren’t fully supported byall browsers When a browser doesn’t support redirects, the customer will get the previ-ous confusing message.

Instead of using browser redirects, you can use a VBScript conditional or SELECT CASEstatement to conditionally display different include files Using the #INCLUDEdirective inthis manner has the same effect as using a redirect without any of the drawbacks Forexample, the script in Listing 4.11 does exactly the same thing as the script in Listing4.10 without using the Redirectmethod

L ISTING 4.11 Avoiding Browser Redirection

1 <%

2 username = TRIM( Request( “username” ) )

3 password = TRIM( Request( “password” ) )

4 IF username = “” OR password = “” THEN

user-Instead of using the Redirectmethod to redirect to the login.asppage, the page isincluded in line 6 with the #INCLUDEdirective Notice that the Endmethod of theResponseobject is used in line 8 to prevent the rest of the page from being displayed

if the login.asppage is displayed

A NALYSIS

Ngày đăng: 13/08/2014, 08:21