Anda di halaman 1dari 102

1

Active Server Pages (ASP)


Outline 33.1 33.2 33.3 33.4 33.5 33.6 33.7 33.8 33.9 33.10 33.11 Introduction How Active Server Pages Work Setup Active Server Page Objects Simple ASP Examples File System Objects Session Tracking and Cookies ActiveX Data Objects (ADO) Accessing a Database from an Active Server Page Server-Side ActiveX Components Web Resources

2004 Prentice Hall, Inc. All rights reserved.

Objectives In this tutorial, you will learn:


To program Active Server Pages using VBScript. To understand how Active Server Pages work. To understand the differences between client-side scripting and server-side scripting. To be able to pass data between Web pages. To be able to use server-side include statements. To be able to use server-side ActiveX components. To be able to create sessions. To be able to use cookies. To be able to use ActiveX Data Objects (ADO) to access a database.
2004 Prentice Hall, Inc. All rights reserved.

33.1 Introduction Server-side technologies


Dynamically creates Web pages
Use client information, server information and information from the Internet

Active Server Pages (ASP)


Microsoft Server-side technology Dynamically build documents in response to client requests Deliver dynamic Web content XHTML, DHTML, ActiveX controls, client-side scripts and Java applets

2004 Prentice Hall, Inc. All rights reserved.

33.2 How Active Server Pages Work Active Server Pages


Processed by scripting engine
Server-side ActiveX control
.asp file extension

Can contain XHTML tags Scripting written with VBScript


JavaScript also used Others (Independent Software Vendors)

Communication with Server


Client HTTP request to server Active server page processes request and returns results

2004 Prentice Hall, Inc. All rights reserved.

33.2 How Active Server Pages Work Active Server Pages,cont.


Communication with Server, cont.
ASP document is loaded into memory asp.dll scripting engine on server Parses (top to bottom)

2004 Prentice Hall, Inc. All rights reserved.

33.3 Setup Web Server


Need to run Web server to use Active Server Pages
IIS 5.0 (Internet Information Services) or higher

Create a virtual directory


Copy files to c:\InetPub\Wwwroot

2004 Prentice Hall, Inc. All rights reserved.

33.4 Active Server Page Objects


Built-in objects
Communicate with a Web browser Gather data sent by HTTP request Distinguish between users
Request
Get or post information Data provided by the user in an XHTML form Access to information stored on client machine Cookies File upload (binary)

Response
Sends information to client XHTML, text

Server
Access to server methods or properties
2004 Prentice Hall, Inc. All rights reserved.

33.4 Active Server Page Objects


Object Name
Request Response

Description Used to access information passed by an HTTP request.

Used to control the information sent to the client. Server Used to access methods and properties on the server. Fig. 25.1 Commonly used ASP objects.

2004 Prentice Hall, Inc. All rights reserved.

33.5 Simple ASP Examples


ASP Scripts
Scripting delimiters
<% %> @LANGUAGE directive

Option Explicit As in VBScript, forces all variables to be declared in advance FormatDateTime Time to display
Now

Format to display in

2004 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11

<% @LANGUAGE = VBScript %> <% ' Fig. 33.2 :

10

' A simple ASP example Option Explicit %>

Scripting delimiter wraps around code clock.asp executed on the server. Processing directive specifying scripting Requires programmer 1.0 language Transitional//EN" explicitly define all variables

Outline
clock.asp (1 of 2)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML

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

12 <html xmlns = "http://www.w3.org/1999/xhtml"> 13 14 15 16 17 18 19 20 21 22 23 24 25 </head> p </style> strong <style type = "text/css"> td { background-color: black; color: yellow } { font-family: arial, sans-serif; font-size: 14pt; color: blue } { font-size: 14pt } <head> <title>A Simple ASP Example</title>

2004 Prentice Hall, Inc.


All rights reserved.

26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 </html> </tr> <td> <% =Time() %> </td> <body>

11

Returns server date and time short for <%= is (Now) as Example</strong></p> a string formatted in Response.write <p><strong>A Simple ASP vbLongDate format <table border = "6">
<tr> <td> <% =FormatDateTime( Now, vbLongDate ) %> </td>

Outline
clock.asp (2 of 2)

Statement</table> for: is short


<%</body> Response.write( Time()) %> Call

2004 Prentice Hall, Inc.


All rights reserved.

12

33.5 Simple ASP Examples


Fig. 33.2 Simple Active Server Page.

2004 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

<!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>A Simple ASP Example</title> <style type = "text/css"> td strong p </style> </head> <body> { background-color: black; color: yellow } { font-family: arial, sans-serif; font-size: 14pt; color: blue } { font-size: 14pt }

13

Outline
HTML generated by clock.asp (1 of 2)

2004 Prentice Hall, Inc.


All rights reserved.

21 22 23 24 25 26 27 28 29 30 31 32 33 34

<p><strong>A Simple ASP Example</strong></p> <table border = "6"> <tr> <td> Thursday, May 24, 2001 </td> <td> 2:22:58 PM </td> </tr> </table> </body>

14

Outline
HTML generated by clock.asp (2 of 2)

35 </html>

2004 Prentice Hall, Inc.


All rights reserved.

15

33.5 Simple ASP Examples ASP processes input


Form information sent by client E-commerce Web site
Use to verify customer information

Server responds to process request Form


Using post method action attribute indicates the .asp file to which the form information is posted Request object retrieves form data

2004 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <!-- Fig. 33.4 : name.html -->

16

Outline
name.html (1 of 2)

<!-- XHTML document that request an ASP document --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Name Request</title> </head> <body> <p style = "font-family: arial, sans-serif"> Enter your name: </p>

2004 Prentice Hall, Inc.


All rights reserved.

19 20 21 22 23 24 25 26 27

<!-- request name.asp when posted --> <form action = "name.asp" method = "post"> <input type = "text" name = "namebox" size = "20" /> <input type = "submit" name = "submitButton" action value = "Enter" /> </form> </body>

17

Outline
set to ASP file where information is posted. name.html (2 of 2)

28 </html>

2004 Prentice Hall, Inc.


All rights reserved.

18

33.5 Simple ASP Examples


Fig. 33.4 XHTML document that requests an ASP.

2004 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11

<% @LANGUAGE = VBScript %>

19

Outline
<% ' Fig. 33.5 : name.asp ' Another simple ASP example Option Explicit %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

name.asp (1 of 2)

12 <html xmlns = "http://www.w3.org/1999/xhtml"> 13 14 15 16 17 18 19 20 21 22 </style> </head> <style type = "text/css"> p { font-family: arial, sans-serif; font-size: 14pt; color: navy } .special { font-size: 20pt; color: green } <head> <title>Name Information</title>

2004 Prentice Hall, Inc.


All rights reserved.

23 24 25 26 27 28 29 30 31 32 </html> </body> <!-- retrieve and display namebox's value --> <p>Hi <% =Request( "namebox" ) %>, </p><br /> <p class = "special">Welcome to ASP!</p> <body>

20

Outline
Request object retrieves

form data from text field namebox

name.asp (2 of 2)

2004 Prentice Hall, Inc.


All rights reserved.

21

33.5 Simple ASP Examples


Fig. 33.5 ASP document that responds to a client request.

2004 Prentice Hall, Inc. All rights reserved.

22

33.6 File System Objects File System Objects (FSOs)


Allow programmer to manipulate files, directories and drives Read and write text Microsoft Scripting Runtime Library (Fig 33.6)
FileSystemObject, File, Folder, Drive and TextStream

Use to create directories, move files, determine whether a Drive exists


FileSystemObject methods (Fig. 33.7)

File object Allows programmer to gather info about files, manipulate files, open files File properties and methods (Fig. 33.8)
2004 Prentice Hall, Inc. All rights reserved.

23

33.6 File System Objects


Object type
FileSystemObject File

Description Allows the programmer to interact with Files, Folders and Drives.

Allows the programmer to manipulate Files of any type. Folder Allows the programmer to manipulate Folders (i.e., directories). Drive Allows the programmer to gather information about Drives (hard disks, RAM diskscomputer memory used as a substitute for hard disks to allow high-speed file operations, CD-ROMs, etc.). Drives can be local or remote. TextStream Allows the programmer to read and write text files. Fig. 33.6 File System Objects (FSOs).

2004 Prentice Hall, Inc. All rights reserved.

24

33.6 File System Objects


Methods
CopyFile CopyFolder

Description Copies an existing File.

Copies an existing Folder. CreateFolder Creates and returns a Folder. CreateTextFile Creates and returns a text File. DeleteFile Deletes a File. DeleteFolder Deletes a Folder. DriveExists Tests whether or not a Drive exists. Returns a boolean. FileExists Tests whether or not a File exists. Returns a boolean. FolderExists Tests whether or not a Folder exists. Returns a boolean. GetAbsolutePathName Returns the absolute path as a string. Fig. 33.7 FileSystemObject methods. (Part 1 of 2)

2004 Prentice Hall, Inc. All rights reserved.

25

33.6 File System Objects


Description GetDrive Returns the specified Drive. GetDriveName Returns the Drive drive name. GetFile Returns the specified File. GetFileName Returns the File file name. GetFolder Returns the specified File. GetParentFolderName Returns a string representing the parent folder name. GetTempName Creates and returns a string representing a file name. MoveFile Moves a File. MoveFolder Moves a Folder. OpenTextFile Opens an existing text File. Returns a TextStream. Fig. 33.7 FileSystemObject methods. (Part 2 of 2) Methods

2004 Prentice Hall, Inc. All rights reserved.

26

33.6 File System Objects


Property/method Property
DateCreated DateLastAccessed DateLastModified Drive Name ParentFolder Path ShortName Size

Description Date. The date the File was created. Date. The date the File was last accessed. Date. The date the File was last modified. Drive. The Drive where the file is located. String. The File name. String. The Files parent folder name. String. The Files path. String. The Files name expressed as a short name. Variant. The size of the File in bytes.

Method Copy the File. Same as CopyFile of FileSystemObject. Delete Delete the File. Same as DeleteFile of FileSystemObject. Move Move the File. Same as MoveFile of FileSystemObject. OpenAsTextStream Opens an existing File as a text File. Returns TextStream. Fig. 33.8 Some common File properties and methods.
Copy

2004 Prentice Hall, Inc. All rights reserved.

27

33.6 File System Objects File System Objects (FSOs)


Path property Contains File path in long name format
ShortName

property

Contains File path in short name format Folder object Allows programmer to manipulate and gather info about directories Folder properties (Fig. 33.9)

2004 Prentice Hall, Inc. All rights reserved.

28

33.6 File System Objects


Property/ method Properties
Attributes DateCreated DateLastAccessed DateLastModified Drive IsRootFolder Name ParentFolder Path ShortName ShortPath Size Type

Description Integer. Value indicating Folders attributes (read only, hidden, etc.). Date. The date the folder was created. Date. The date the folder was last accessed. Date. The date the folder was last modified. Drive. The Drive where the folder is located. Boolean. Indicates whether or not a Folder is a root folder. String. The Folders name. Folder. The Folders parent folder. String. The Folders path. String. The Folders name expressed as a short name. String. The Folders path expressed as a short path. Variant. The total size in bytes of all subfolders and files.

Fig. 33.9

String. The Folder type. Some Folder properties and methods. (Part 1 of 2)

2004 Prentice Hall, Inc. All rights reserved.

29

33.6 File System Objects


Property/method Methods
Delete Move Copy

Description

Fig. 33.9

Delete the Folder. Same as DeleteFolder of FileSystemObject. Move the Folder. Same as MoveFolder of FileSystemObject. Copy the Folder. Same as CopyFolder of FileSystemObject. Some Folder properties and methods. (Part 2 of 2)

2004 Prentice Hall, Inc. All rights reserved.

30

33.6 File System Objects File System Objects (FSOs)


IsRootFolder property Indicates whether folder is the root folder for the Drive If not: Method ParentFolder Retrieves parent folder Method Size Returns the total bytes the folder contains (includes subfolders)

2004 Prentice Hall, Inc. All rights reserved.

31

33.6 File System Objects File System Objects (FSOs)


Drive object (Fig. 33.10)
Gather information about drives Property DriveLetter Contains drive letter Property SerialNumber Contains drive serial number Property FreeSpace Contains number of available bytes

2004 Prentice Hall, Inc. All rights reserved.

32

33.6 File System Objects


Property
AvailableSpace DriveLetter

Description Variant. The amount of available Drive space in bytes.

String. The letter assigned to the Drive (e.g., C). DriveType Integer. The Drive type. Constants Unknown, Removable, Fixed, Remote, CDRom and RamDisk represent Drive types and have the values 05, respectively. FileSystem String. The file system Drive description (FAT, FAT32, NTFS, etc.). FreeSpace Variant. Same as AvailableSpace. IsReady Boolean. Indicates whether or not a Drive is ready for use. Path String. The Drives path. RootFolder Folder object. The Drives root Folder. SerialNumber Long. The Drive serial number. TotalSize Variant. The total Drive size in bytes. VolumeName String. The Drive volume name. Fig. 33.10 Drive properties.

2004 Prentice Hall, Inc. All rights reserved.

33

33.6 File System Objects File System Objects (FSOs)


TextStream object (Fig. 33.11) Manipulate text files

2004 Prentice Hall, Inc. All rights reserved.

34

33.6 File System Objects


Property/ Method Properties
AtEndOfLine AtEndOfStream Column Line

Description

Boolean. Indicates whether the end of a line has been encountered. Boolean. Indicates whether the end of file has been encountered. Integer. Returns the characters position in a line. Integer. Returns the current line number. String. Returns a specified number of characters from the file referenced by the TextStream object. String. Returns the entire contents of the file referenced by the TextStream object. TextStream methods and properties. (Part 1 of 2)

Methods
Read ReadAll

Fig. 33.11

2004 Prentice Hall, Inc. All rights reserved.

35

33.6 File System Objects


Property/ Method Methods, cont.
ReadLine Write WriteBlankLines WriteLine Skip SkipLine Close

Description

String. Returns one line from the file referenced by the TextStream object. String. Writes text to the file referenced by the TextStream object. String. Writes newline characters to the file referenced by the TextStream object. String. Writes one line to the file referenced by the TextStream object. Variant. Skips a specified number of characters while reading from the file referenced by the TextStream object. Variant. Skips a line of characters while reading from the file referenced by the TextStream object. Close the file referenced by the TextStream object.

Fig. 33.11

TextStream methods and properties. (Part 2 of 2)

2004 Prentice Hall, Inc. All rights reserved.

36

33.6 File System Objects Creating a guestbook


XHTML Form hidden field
Determine if page loaded by form submission

Write data to text file


ServerVariables APPL_PHYSICAL_PATH OpenTextFile

Append mode
8

2004 Prentice Hall, Inc. All rights reserved.

37

33.6 File System Objects Creating a guestbook, cont.


Name returned as mailto: URL
Request object

Chr function Generate characters from ASCII code

Always Close files

2004 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10

<% @LANGUAGE = VBScript %>

38

Outline
<% ' Fig. 33.12 : guestbook.asp ' Demonstrating File System Objects Option Explicit %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

guestbook.asp (1 of 5)

11 <html xmlns = "http://www.w3.org/1999/xhtml"> 12 13 14 15 16 17 18 19 20 21 22 23 24 <style type = "text/css"> hr td p </style> </head> <body> { size: 1; color: blue } { font-size: 12pt } { font-size: 14pt; color: blue } table { text-align: center } <head> <title>GuestBook Example</title>

.font { font-family: arial, sans-serif }

2004 Prentice Hall, Inc.


All rights reserved.

25 <% 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 %> 44 45 <% 46 47 48 49 ' build the mailtoUrl & & <hr /> ' Print a thank you Call Response.Write( "Thanks for your entry, " & _ Request( "username" ) & "!" ) ' Check if this request is after the user has posted the form If Request( "hiddenInput" ) = "true" Then ' instantiate a FileSystemObject Set fileObject = Server.CreateObject( _ "Scripting.FileSystemObject" ) Dim fileObject, textFile, guestBook, mailtoUrl ' get physical path for this ASP page and ' concatenate guestbook.txt to it & "\guestbook.txt"

39

Outline

Set is required to establish a

variable in VBScript

guestbook = Request.ServerVariables(

guestbook.asp Pass Request method (2 of 5) "APPL_PHYSICAL_PATH" ) _ ServerVariables server key Creating a FSO instance APPL_PHYSICAL_PATH assigned to reference
fileObject

Concatenated with file name guestbook.txt

Request object retrieves hiddenInput value and tests it string string true Printsagainst followed by

users name input in the form

mailtoUrl = Date() & " <a href = " & Chr( 34 ) _

Submitted name and email "mailto:" & Request( "email" ) & Chr( 34 ) _ are combined and assigned to Pass value 34 into VBScript ">" & Request( "username" ) & "</a>: " string mailtoUrl Displays a mailto:current Date() assigns link. Chr function to produce double Request retrieves email of server date to beginning and quotes () username mailtoUrl
2004 Prentice Hall, Inc.
All rights reserved.

50 51 52 53 54 55 56 57 58 59 60 61 62 %> 63 64 65 66 67 68 69 70 71 72 73 74 </tr> <!-- write form to the client --> <form action = "guestbook.asp" method = "post"> <table> <tr> <td>Your Name: </td> ' write data to guestbook.txt Call textFile.WriteLine( "<hr Request( "comment" ) ) Call textFile.Close() End If ' open the guestbook, 8 is for appending ' create the guestbook if it does not exist Set textFile = _ fileObject.OpenTextFile( guestbook, 8, True )

40

Outline
guestbook.asp (3 of 5)

Method OpenTextFile retrieves TextStream object />" & mailtoUrl & _ Contstantforindicates file 8 accessing append mode (writing to guestbook.txt the end of the file.)
Close()TextStream method method closes the file WriteLine writes to guestbook.txt

<p>Please leave a message in our guestbook.</p>

Form post action to .asp page

<td><input class = "font" type = "text" size = "60" name = "username" /></td>

2004 Prentice Hall, Inc.


All rights reserved.

75 76 77 78 79 80 81 82 83 84 85 86 87 88 <tr> <td>Tell the world: </td> <td><textarea name = "comment" rows = "3" cols = "50"> </td> </tr> <tr> <td>Your email address:</td> <td><input class = "font" type = "text" size = "60" name = "email" value = "user@isp.com" />

41

Outline
guestbook.asp (4 of 5)

Form contains two text fields and text area for user input

89 Replace this text with the information 90 you would like to post.</textarea></td> 91 92 93 94 95 96 97 98 99 </form> </tr> </table>

Passes parameter
hiddenInput value true

<input type = "submit" value = "submit" /> <input type = "reset" value = "clear" /> <input type = "hidden" name = "hiddenInput" value = "true" />

2004 Prentice Hall, Inc.


All rights reserved.

100 <% 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 %> 116 117 118 119 </html> </body> End If ' read the entries from the file and write them to ' the client. Call Response.Write( "Guestbook Entries:<br />" & _ textFile.ReadAll() ) Call textFile.Close() ' check if the file exists If fileObject.FileExists( guestBook ) = True Then

42

Outline
guestbook.asp (5 of 5)

FSO object FileExists checks if guestbook.txt ' open the guestbook, "1" is for reading exists. Set textFile = fileObject.OpenTextFile( guestbook, 1 )

TextStream and ReadAll

Read entries from entire methods read guestbook.txt and write writes contents of Response.Write guestbook.txt XHTMLtext to client Contains to the client.

XHTML markup rendered on client browser.

2004 Prentice Hall, Inc.


All rights reserved.

43

33.6 File System Objects


Fig. 33.12 Guestbook Active Server Page.

2004 Prentice Hall, Inc. All rights reserved.

44

33.6 File System Objects


Fig. 33.12 Guestbook Active Server Page.

2004 Prentice Hall, Inc. All rights reserved.

1 2

<hr />5/24/2001 <a href = "mailto:tem@deitel.com">tem</a>:

ASP is a great tool ASP is my

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

45

Outline
XHTML generated by guestbook.asp (1 of 1)

2004 Prentice Hall, Inc.


All rights reserved.

46

33.6 File System Objects


Key name Description APPL_PHYSICAL_PATH Returns the physical path. HTTPS Boolean. Determines whether the request came in through SSL (Secure Sockets Layer). REMOTE_ADDR Clients DNS name or IP address. REQUEST_METHOD Request method (i.e., get and post). SERVER_NAME Servers hostname (DNS or IP address). HTTP_USER_AGENT Returns information about the client making the request. HTTP_COOKIE Returns cookies residing on the client. Fig. 33.13 Some server variable keys.

2004 Prentice Hall, Inc. All rights reserved.

47

33.7 Session Tracking and Cookies Session Tracking and Cookies


Helps server to distinguish between clients Provide custom content
Shopping cart Marketing/advertising SessionID Assigned by server to each unique session Compared with sessionIDs stored in server Session object Timeout property Length of session before it expires Abandon property Terminates individual session
2004 Prentice Hall, Inc. All rights reserved.

48

33.7 Session Tracking and Cookies ASP application


Multiple ASP pages linked with session variables Example
instantpage.asp

Form, requests information from the user Posted to process.asp


process.asp

Redirects user to instantpage.asp if errors exist Otherwise creates users ASP page Stores message in session variable welcomeBack Every time user submits the form

2004 Prentice Hall, Inc. All rights reserved.

49

33.7 Session Tracking and Cookies Server-side include


Commands embedded in XHTML documents Add dynamic content Places a .shtml include file within another file
Physical or virtual path
<!--#include file = includes\file.shtml -->

Not all Web servers support


Written as comment

Performed before scripting code is interpreted.


ASP page cannot determine which includes to use

Can contain scripting code


Must use <script> tag or <% %> delimiters

2004 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11

<% @LANGUAGE = VBScript %>

50

Outline
<% ' Fig. 33.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">

instantpage.asp (1 of 4)

12 <html xmlns = "http://www.w3.org/1999/xhtml"> 13 14 15 16 17 18 19 20 21 22 23 24 25 </head> </style> <style type = "text/css"> table { text-align: center; font-size: 12pt; color: blue; font-size: 12pt; font-family: arial, sans-serif } <head> <title>Instant Page Content Builder</title>

2004 Prentice Hall, Inc.


All rights reserved.

26 27 28 29 30 31 32 33 <% ' if process.asp posted an error, print the error 34 35 36 37 38 39 40 41 42 %> 43 44 45 46 47 48 ' message. If Session( "errormessage" ) <> "no error" Then Call Response.Write( Session( "errorMessage" ) ) ' otherwise, print the welcome back message, if any Else Call End If <!-- include the header <h2>Instant Page Content Builder</h2> --> <!-- #include virtual = "/includes/header.shtml" --> <body>

51

Server-side include

Outline
instantpage.asp (2 of 4)

First time page is executed, Session object Response.Write( Session( "welcomeBack" ) ) line 35 returns true retrieves variable value errorMessage session If true, variable used for error errorMessage messages
If statement tests errorMessage equality to no error. Return True or False.

value is written to client welcomeBack session errorMessage never has a variable displays value unless errors are <!-- a form Else, WelcomeBack value is the user --> to get the information from welcome back message encountered <form action = "process.asp" method = "post"> written to the client to returning users
<table> <tr> <td>Your Name: </td>

Requests process.asp when form is posted

2004 Prentice Hall, Inc.


All rights reserved.

49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72

<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"

52

Outline
instantpage.asp (3 of 4)

2004 Prentice Hall, Inc.


All rights reserved.

73

cols = "50">

74 Replace this text with the 75 information you would like to post.</textarea></td> 76 77 78 79 80 81 82 83 84 <!-- #include virtual = "/includes/footer.shtml" --> </body> </tr> </table>

53

Outline
instantpage.asp (4 of 4)

Server-side include <input type = "submit" value = "submit" />


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

85 </html>

2004 Prentice Hall, Inc.


All rights reserved.

54

33.7 Session Tracking and Cookies


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

2004 Prentice Hall, Inc. All rights reserved.

55

33.7 Session Tracking and Cookies


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

2004 Prentice Hall, Inc. All rights reserved.

56

33.7 Session Tracking and Cookies


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

2004 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5

<!-- Fig. 33.16: header.shtml <hr style = "color: blue" />

-->

57

<!-- Server-side include file containing XHTML --> <img height = "100" src = "/images/bug2bug.gif" alt = "Bug" /> <hr style = "color: blue" />

Outline
header.shtml (1 of 1)

2004 Prentice Hall, Inc.


All rights reserved.

1 2 3 4 5 6 7 8

<!-- Fig. 33.17: footer.shtml <hr style = "color: blue" /> <a style = "text-align: center"

-->

58

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

Outline
footer.shtml
server-side include file for the document footer

href = "mailto:orders">ordering information</a> <a style = "text-align: center" href = "mailto:editor">contact the editor</a><br /> <hr style = "color: blue" />

2004 Prentice Hall, Inc.


All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

<% @LANGUAGE = VBScript %>

59

Outline
<% ' Fig. 33.18 : process.asp ' ASP document that creates user's ASP document Option Explicit %> <%

process.asp (1 of 6)

If field is empty or contains default string yourfilename, lines 19Dim message, assign XHTML error 21 q message to variable If statement validates q = Chr( 34 ) ' assign quote character to q message. Session( "errorMessage" ) = "no error"contents of text field.
' check to make sure that they have entered a ' valid filename If ( LCase( Request( "filename" ) ) = "yourfilename" ) _Assign Or Request( "filename" ) = "" Then message = "<p style = " & q & "color: red" & q & _ Session( "errorMessage" ) = message Call Server.Transfer( "instantpage.asp" ) End If Dim directoryPath, filePath, fileObject, fileName

message value to

session variable
errorMessage

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

Server method Transfer requests


instantpage.asp
2004 Prentice Hall, Inc.
All rights reserved.

26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 ' 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>" filePath Session( "errorMessage" ) = message method. Call Server.Transfer( "instantpage.asp" ) End If ' build path for text file filePath = directoryPath & "\" & fileName fileName = Request( "filename" ) & ".asp" directoryPath = _ Request.ServerVariables( "APPL_PHYSICAL_PATH" ) ' Create a FileSystem Object Set fileObject =

60 Request.ServerVariables Server.CreateObject( _

retrieves "Scripting.FileSystemObject" )physical

path

FSO object is created if valid Outline user name is entered and assigned Builds fileName by reference fileObject concatenating process.asp filename to the .asp (2 of 6) file extension Specify server path where ASP file is written

If file exists, variable errorMessage value is set to XHTML containing error message

passed FileExists Determines if file exists.

Server.Transfer method requests instantpage.asp

2004 Prentice Hall, Inc.


All rights reserved.

48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73

' 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 = "%" & ">"

61

Outline
process.asp (3 of 6)

Construct XHTML for header Assigns XHTML for welcome ' build the header. back message to welcomeBack Assign ASP scripting the text ' vbCrLf inserts a carriage return/linefeed into session variable delimitersmore readable to string variables ' string which makes the XHTML code openMark and closeMark 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 = " _

2004 Prentice Hall, Inc.


All rights reserved.

74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93

& 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" & _

62

Outline
process.asp (4 of 6)

footer variable 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>"

assigned to XHTML footer contents Form values retrieved using Request object

2004 Prentice Hall, Inc.


All rights reserved.

94 95 96 97 98 99 100 101 %> 102

' create the ASP file Set textFile = fileObject.CreateTextFile( filePath, False ) With textFile Call .WriteLine( header & Request( "content" ) & _ footer )

63

Outline
process.asp (5 of 6)

Lines Call .Close()


End With

103-129 send XHTML to client that contains link to created page

103 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 104 105 106 <html xmlns = "http://www.w3.org/1999/xhtml"> 107 108 109 110 111 112 113 114 115 116 117 118 </head> <style type = "text/css"> h2 { font-family: arial, sans-serif; text-align: center } </style> <head> <!-- use the title given by the user --> <title>File Generated: <% =fileName %></title> "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

2004 Prentice Hall, Inc.


All rights reserved.

119 120 121 122 123 124 125 126 127 128

<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>

64

Outline
process.asp (6 of 6)

129 </html>

2004 Prentice Hall, Inc.


All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

<% @LANGUAGE = VBScript %> <% ' aboutme.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>About Me</title> </head> <body> <!-- Fig. 33.16: header.shtml <hr style = "color: blue" /> <img height = "100" src = "/images/bug2bug.gif" alt = "Bug" /> <hr style = "color: blue" /> <h2 style = "text-align: center"><em>About Me</em></h2> <br /> <br /><br /><br /> --> <!-- Server-side include file containing XHTML -->

65

Outline
aboutme.asp (1 of 2)

20 This page contains lots of exciting and interesting information about me! 21 22 You have requested this page on 10/15/2003, 23 at 11:45:47 AM. 24 25 <!-- Fig. 33.17: footer.shtml --> <!-- Server-side include file containing XHTML -->

2004 Prentice Hall, Inc.


All rights reserved.

26 27 28 29 30 31 32 33

<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>

66

Outline
aboutme.asp (2 of 2)

34 </html>

2004 Prentice Hall, Inc.


All rights reserved.

67

33.7 Session Tracking and Cookies


Fig. 33.20 Welcome back message displayed by instantpage.asp.

2004 Prentice Hall, Inc. All rights reserved.

68

33.7 Session Tracking and Cookies


Fig. 33.21 Error message generated by instantpage.asp.

2004 Prentice Hall, Inc. All rights reserved.

69

33.8 ActiveX Data Objects (ADO) ADO


Enables database connectivity Part of Universal Data Access architecture
OLE DB provides low-level access ODBC allows C programs to access databases ADO allows web applications to access databases

Provides pre-built objects for use in ASP and VBScript


Collections

2004 Prentice Hall, Inc. All rights reserved.

70

33.8 ActiveX Data Objects (ADO)


Fig. 33.22 Microsofts UDA architecture.

Application or Browser

ADO OLE DB ODBC Relational data sources Non-relational data sources Legacy data

2004 Prentice Hall, Inc. All rights reserved.

71

33.8 ActiveX Data Objects (ADO)


Fig. 33.23 Portion of the ADO object model.

Connection

Command
Errors RecordSet

Parameters Error Fields

Parameter

Field

2004 Prentice Hall, Inc. All rights reserved.

72

33.8 ActiveX Data Objects (ADO)


Object/Collection Description
Connection object Command object Parameter object Parameters collection Error object Errors collection Recordset object Field object Fields collection Property object Properties collection Record object Stream object Connects to the data source. Contains the query that interacts with the database (the data source) to manipulate data. Contains information needed by a Command object to query the data source. Contains one or more Parameter objects. Created when an error occurs while accessing data. Contains one or more Error objects. Contains zero or more records that match the database query. Collectively, this group of records is called a recordset. Contains the value (and other attributes) of one data source field. Contains one or more Field objects. Contains a characteristic of an ADO object. Contains one or more Property objects. Contains a single row of a Recordset. Contains a stream of binary data.

Fig. 33.24

Some ADO object and collection types.

2004 Prentice Hall, Inc. All rights reserved.

73

33.9 Accessing a Database from an Active Server Page Web applications


Communicating with databases
Use ActiveX Data Objects (ADO) Provides uniform way for programs to connect with databases

Three-tier distributed applications


User interface Created with XHTML, DHTML or XML Contains ActiveX controls, client-side scripts, Java applets Communicate directly with business logic Business logic Database access May reside on separate computers
2004 Prentice Hall, Inc. All rights reserved.

74

33.9 Accessing a Database from an Active Server Page


Web applications, cont.
Three-tier distributed applications, cont.
Web servers build middle tier Provide business logic Manipulates databases Communicates with client Web browsers

ASP communications with databases


Use SQL-based queries ADO handled specifics Through OLE DB Databases provide data source for dynamic content Allows users who are not familiar with Web languages to create Web pages Restrict access Password protection Query Access database
2004 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24

<% @LANGUAGE = VBScript %>

75

Outline
<% ' Fig. 33.25 : database.asp ' ASP document for interacting with the database Option Explicit

Ignores errors until end of script Dim connection, loginData Server method When Open finishes CreateObject creates executing, points to first ' provide error handling code ADODB.Connection Declares record session On Error Resume Next Method Open opensor EOF if no variable records Session( "errorString" ) = "" database specified bywere found errorString ODBC System DSN errorHandlerLog loginData(login) is set reference Set connection = Server.CreateObject( "ADODB.Connection" ) to an ADODB.recordset processes errors Call connection.Open( "login" ) Open method is passed string object Call errorHandlerLog() containing SQL query and ADODB.Connection object errorHandlerLog ' create the record set called again
Set loginData = Server.CreateObject( "ADODB.Recordset" ) Call loginData.Open( Session( "query" ), connection ) Set Session( "loginData" ) = loginData Call errorHandlerLog()

database.asp (1 of 2)

Sets session variable loginData to variable loginData which references the ADODB.recordset containing all records matching SQL query
2004 Prentice Hall, Inc.
All rights reserved.

25 26 27 28 29 30 31 32 33 34 35 36 37 %>

Sub errorHandlerLog()

76

Outline If true, errorString variable is assigned XHTML text containing database.asp errorString = Session( "errorString" ) Error number and message error & _ number and message (2 of 2) errorString = errorString & "<p class = " concatenated to variable Chr( 34 ) & "error" & Chr ( 34 ) & ">Error (" _ errorString Err object Number property & Err.Number & ") in " & Err.Source & "<br />" & _ contains VBScript error Err.Description & "</p><br />" number. Tests if error has Session( "errorString" ) = errorString occurred.
Dim errorString End If End Sub

If Err.Number <> 0 Then

2004 Prentice Hall, Inc.


All rights reserved.

77

33.9 Accessing a Database from an Active Server Page


Fig. 33.26 Error messages sent to login.asp by database.asp.

2004 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10

<% @LANGUAGE = VBScript %>

78

Outline
<% ' Fig. 33.27 : login.asp ' ASP document to login to instantpage.asp Option Explicit ' create the SQL query Session( "query" ) = "SELECT loginID FROM Users" Call Server.Execute( "database.asp" )

login.asp (1 of 7)

11 %> 12 13 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 14 15

Assigns SQL query to session variable "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> Executes database.asp to retrieve query login IDs from the database

16 <html xmlns = "http://www.w3.org/1999/xhtml"> 17 18 19 20 21 22 23 24 25 <style type = "text/css"> table { text-align: center; font-size: 12pt; color: blue; font-size: 12pt; <head> <title>Login Page</title>

2004 Prentice Hall, Inc.


All rights reserved.

26 27 28 29 30 31 32 33 34 35 <% 36 37 38 39 40 41 42 <% 43 44 45 46 47 End If <body> </head> </style>

font-family: arial, sans-serif } .error { color: red }

79

Outline
login.asp (2 of 7)

<!-- #include virtual="/includes/header.shtml" --> If Session( "errorString" ) = "" Then ' if this is a return after a failed attempt, ' print an error If Session( "loginFailure" ) = True Then %> <p class = "error">Login attempt failed,

Tests please try again</p>

if session variable errorString value is empty string

' begin the form %> <p>Please select your name and enter your password to login:</p><br />

Lines 39-41 test is session variable loginFailure is True

2004 Prentice Hall, Inc.


All rights reserved.

48 49 50 51 52 53 54 55 56 57 58 59 60 <% 61 62 63 64 65 66 %> 67 68 69 70

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

80

Outline
<!-- format the form using a table --> <table border = "0"> <tr> <td>Name:</td> <td> <select name = "loginID"> <option value = "noSelection"> Select your name</option> Requests loginID

select structure builds dropdown list of loginIDs

login.asp (3 of 7)

cookie

If Request.Cookies( "loginID" ) <> "" Then Call BuildReturning() Else Call BuildNewUser() End If </select> </td> </tr>

Selects the returning users login ID option Build loginID options

2004 Prentice Hall, Inc.


All rights reserved.

71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 <% 88 89 90 91 %> 92 </body> 93 </html> 94 Else

<tr> <td>Password:</td> <td><input type = "password" name = "password" /></td> </tr> <tr> <td></td> <td align = "left"> <input type = "submit" value = "Log Me In" /> </td> </tr> </table> </form> <!-- #include virtual="/includes/footer.shtml" -->

81

Outline
login.asp (4 of 7)

Call Response.Write( Session( "errorString" ) ) End If

If false, print error message to user

2004 Prentice Hall, Inc.


All rights reserved.

95 <% 96 97 98 99 100 101 102 103 104 105 106 107 108 109 %> 110 <% 111 112 113 114 115 116 117 118 119 ' if the current record's loginID is equal to ' the loginID cookie, then it is the loginID of ' the returning user, and thus we need to write ' selected for this option; in this case we also ' need to signal that we have written selected ' for an option by setting found to True. While Not loginData.EOF ' create this record's dropdown entry <option ' if we did not write selected for ' before If ( Not found ) Then ' pull user names from the record set to populate the ' dropdown list found = False Set loginData = Session( "loginData" ) ' builds the option items for loginIDs and writes ' selected for the loginID of the returning user Sub BuildReturning() Dim found, loginData

82

Outline
login.asp (5 of 7)

Tests for EOF


found set to False If statement tests whether before loop option needs to be any option selected

2004 Prentice Hall, Inc.


All rights reserved.

120 121 122 123 124 125 126 127 %> 128 129 <% 130 131 132

If Request.Cookies( "loginID" ) _ = loginData( "loginID" ) Then Call Response.Write( "selected = " & _ Chr( 34 ) & "selected" & Chr( 34 ) ) found = True End If End If

83

Outline If statement writes selected for an


option login.asp (6 of 7)

Once selected is Determines whether current option, written for an value = "<% =loginData( "loginID" ) %>"> records loginID field is found set to true <% =loginData( "loginID" ) %></option> equal to loginID cookie
Call loginData.MoveNext()

Wend End Sub

2004 Prentice Hall, Inc.


All rights reserved.

133 134 135 136 137 138 139 140 141 142 143 144 %> 145 146 <% 147 148 149 %>

' builds the option items for loginIDs without writing ' selected for any loginID Sub BuildNewUser() Dim loginData Set loginData = Session( "loginData" ) ' pull user names from the record set to populate the Increments ' dropdown list While Not loginData.EOF ' create this record's dropdown entry <option value = "<% =loginData( "loginID" ) %>"> <% =loginData( "loginID" ) %></option> Call loginData.MoveNext() Wend End Sub

84

Outline
login.asp (7 of 7) the record set pointer to next record

Writes option display as while loop (lines 107-130) ID current login iterates through loginDatas records Sets option value to current login ID

2004 Prentice Hall, Inc.


All rights reserved.

85

33.9 Accessing a Database from an Active Server Page


Fig. 33.27 ASP document that allows the user to log in to a site.

2004 Prentice Hall, Inc. All rights reserved.

86

33.9 Accessing a Database from an Active Server Page


Fig. 33.27 ASP document that allows the user to log in to a site.

2004 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24

<% @LANGUAGE = VBScript %>

87 password

Check whether <% ' Fig. 33.28 : submitlogin.asp


Option Explicit

Outline
submitlogin.asp
(1 of 2)

field is empty or and password ' ASP document to check user's usernameid
loginID field contains

default value
' test if a user name and a password were If Request( "password" ) = "" Or _ Request( "loginID" ) = "noSelection" Session( "loginFailure" ) = True Call Server.Transfer( "login.asp" ) End If Dim connection, loginData ' create the SQL query Session( "query" ) = _ "SELECT * FROM Users WHERE loginID = '" & _ Request( "loginID" ) & "'" Call Server.Execute( "database.asp" ) Set loginData = Session( "loginData" )

If so, variable
loginFailure set to true, client redirected back Then to login.asp

' entered. If not, transfer back to the login page.

Checks password against specifies a WHERE the password in recordset condition on which records are selected
Sets reference loginData to Executes database.asp to sessiondatabase loginData query variable (contains records matching query.)

2004 Prentice Hall, Inc.


All rights reserved.

25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 %>

If Request( "password" ) = loginData( "password" ) Then

88

Sets cookies expiration date to ' password is OK, adjust loginFailure current date plus 3 days
Session( "loginFailure" ) = False

Outline
Sets session variable If true, line writes forms loginID loginFailure value submitlogin.asp value as cookie named loginID to False
(2 of 2)

' write a cookie to recognize them the next time they ' go to login.asp Response.Cookies( "loginID" ) = Request( "loginID" ) ' give it three days to expire

Response.Cookies( "loginID" ).Expires = Date() + 3 ' send them to instantpage.asp Otherwise loginFailure Call Else Session( "loginFailure" ) = True Call Server.Transfer( "login.asp" ) End If

Calls Server method Transfer to redirect client to instantpage.asp

set to True Server.Transfer( "instantpage.asp" ) and client is redirected to login.asp

2004 Prentice Hall, Inc.


All rights reserved.

89

33.9 Accessing a Database from an Active Server Page


Fig. 33.28 ASP document that validates user login.

2004 Prentice Hall, Inc. All rights reserved.

90

33.9 Accessing a Database from an Active Server Page


Fig. 33.28 ASP document that validates user login.

2004 Prentice Hall, Inc. All rights reserved.

91

33.9 Accessing a Database from an Active Server Page


Fig. 33.29 Cookies folder before and after cookie creation.

2004 Prentice Hall, Inc. All rights reserved.

92

33.10 Server-Side ActiveX Components ActiveX controls on the server with no GUI
Make features available in ASP AdRotator ActiveX component
Rotates advertisements on a Web page Randomly displays one of several advertisements Minimizes space on a Web page committed to advertisements Client does not have to support ActiveX technologies (on the server)

PageCounter ActiveX component


Page hit counter

2004 Prentice Hall, Inc. All rights reserved.

93

33.10 Server-Side ActiveX Components


Description MSWC.BrowserType ActiveX component for gathering information about the clients browser (e.g., type, version). MSWC.AdRotator ActiveX component for rotating advertisements on a Web page. MSWC.NextLink ActiveX component for linking Web pages together. MSWC.ContentRotator ActiveX component for rotating HTML content on a Web page. MSWC.PageCounter ActiveX component for storing the number of times a Web page has been requested. MSWC.Counters ActiveX components that provide general-purpose persistent counters. MSWC.MyInfo ActiveX component that provides information about a Web site (e.g., owner name, owner address). Scripting.FileSystemObje ActiveX component that provides an object library for ct accessing files on the server or on the servers network. ActiveX Data Objects (ADO) ActiveX components that provide an object library Data Access Components for accessing databases. Fig. 33.30 Some server-side ActiveX components. Component name

2004 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11

<% @LANGUAGE = VBScript %>

94

Outline
<% ' Fig. 33.31 : component.asp ' Demonstrating Server-side ActiveX Components Option Explicit %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

component.asp (1 of 4)

12 <html xmlns = "http://www.w3.org/1999/xhtml"> 13 14 15 16 17 18 19 20 21 22 23 24 <p> <strong style = "font-family: arial, sans-serif"> Server-side ActiveX Components </strong> <body> <head> <title>ActiveX Component Example</title> </head>

2004 Prentice Hall, Inc.


All rights reserved.

25 <% 26 27 28 29 30 31 32 33 34 35 36 37 38 39 %> 40 41 42 43 <% 44 45 46 47 %> 48 49 50 <script language = "JavaScript"> alert( "Client browser supports JavaScript!" ); </script> If browser.JavaScript = True Then End If If browser.VBScript = True Then ' create a BrowserType object Set browser = Server.CreateObject( "MSWC.BrowserType" ) ' use config.txt to send an advertisement to theCreates client Call Response.Write( _ rotator.GetAdvertisement( "config.txt" ) ) Set Dim rotator, browser, information, counter ' create an AdRotator object

95

Outline
component.asp (2 of 4)

Sends advertisement as HTML to client. Method GetAdvertisement called using reference rotator. rotator = Server.CreateObject( "MSWC.AdRotator" ) Retrieves advertisements from config.txt

AdRotator component instance, assigns it reference rotator

Obtains information about users browser


<script language = "VBScript"> Call Msgbox( "Client browser supports VBScript!" ) </script>

Check property VBScript value

Test JavaScript property

2004 Prentice Hall, Inc.


All rights reserved.

51 <% 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 %> ' create Page Counter Object Set counter = Server.CreateObject( "MSWC.PageCounter" ) Call counter.PageHit() ' page has been "hit" If browser.Cookies Then information = information & "enabled</p><br />" Else information = information & "disabled</p><br />" End If End If

96 BrowserType objects Browser, Version and MinorVer properties

Outline
Passes server variable key component.asp HTTP_USER_AGENT(3 of 4) to ServerVariables, obtains string containing user information

' get client's browser information

information = "<p>Your browser information is:<br />" & _ Request.ServerVariables( "HTTP_USER_AGENT" ) & _ "<br />Browser: " & browser.Browser & " Version: " & _ browser.Version & " Minor version: " & _ browser.MinorVer & "<br />Cookies are "

can obtain similar client information

Tests Cookies property to determine if browser supports cookies

Call Response.Write( information )

Increments number of hits by one

2004 Prentice Hall, Inc.


All rights reserved.

73 74 75 76 77 78

</p>

Returns number of hits


<p style = "color: blue; font-size: 12pt"> This page has been visited <% =counter.Hits() %> times!</p> </body>

97

Outline

component.asp (4 of 4)

79 </html>

2004 Prentice Hall, Inc.


All rights reserved.

98

33.10 Server-Side ActiveX Components


Fig. 33.31 Demonstrating server-side ActiveX components.

2004 Prentice Hall, Inc. All rights reserved.

99

33.10 Server-Side ActiveX Components


Fig. 33.31 Demonstrating server-side ActiveX components.

2004 Prentice Hall, Inc. All rights reserved.

100

33.10 Server-Side ActiveX Components


Fig. 33.31 Demonstrating server-side ActiveX components.

2004 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9

REDIRECT redirect.asp width 54 height 36 border 1 * /images/us.gif United States Information 20

101

Header contains REDIRECT file URL Image URL, destination URL, Advertisement dimensions Asterisk separates header ratio alt value, image display from advertisements

Outline
config.txt (1 of 1)

http://www.odci.gov/cia/publications/factbook/geos/us.html

10 /images/france.gif 11 http://www.odci.gov/cia/publications/factbook/geos/fr.html 12 France Information 13 20 14 /images/germany.gif 15 http://www.odci.gov/cia/publications/factbook/geos/gm.html 16 Germany Information 17 20 18 /images/italy.gif 19 http://www.odci.gov/cia/publications/factbook/geos/it.html 20 Italy Information 21 20 22 /images/spain.gif 23 http://www.odci.gov/cia/publications/factbook/geos/sp.html 24 Spain Information 25 20

2004 Prentice Hall, Inc.


All rights reserved.

1 2 3 4 5 6 7 8 9

<% @LANGUAGE = VBScript %>

102

Outline
<% ' Fig. 33.33 : redirect.asp ' Redirection Page for AdRotator Component Option Explicit Call Response.Redirect( Request( "url" ) ) %>

redirect.asp (1 of 1)

2004 Prentice Hall, Inc.


All rights reserved.

Anda mungkin juga menyukai