Transcript Document

1
Chapter 33 - 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.
2
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.
3
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.
4
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.
5
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.
6
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.
7
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.
8
33.4 Active Server Page Objects
Object Name
Request
Description
Used to access information passed by an HTTP request.
Response
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.
9
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
<% @LANGUAGE = VBScript %>
2
3
<%
' Fig. 33.2 :
5
' A simple ASP example
6
Option Explicit
%>
8
9
10
Outline
Scripting delimiter
wraps around code
clock.asp
executed on the server.
4
7
10
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML
clock.asp
(1 of 2)
Processing directive
specifying scripting
Requires programmer
1.0 language
Transitional//EN"
explicitly define all variables
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
11
12 <html xmlns = "http://www.w3.org/1999/xhtml">
13
14
15
<head>
<title>A Simple ASP Example</title>
16
17
18
<style type = "text/css">
td
color: yellow }
19
20
{ background-color: black;
strong
{ font-family: arial, sans-serif;
font-size: 14pt; color: blue }
21
22
p
23
</style>
{ font-size: 14pt }
24
25
</head>
 2004 Prentice Hall, Inc.
All rights reserved.
26
27
28
29
30
11
<body>
Returns server date and
time
“<%=
“ is short for
(
Now
)
as
a
string
formatted
in
Response.write
<p><strong>A Simple ASP Example</strong></p>
format
<table bordervbLongDate
= "6">
<tr>
31
Outline
clock.asp
(2 of 2)
<td>
32
<% =FormatDateTime( Now, vbLongDate ) %>
33
</td>
34
35
<td>
36
<% =Time() %>
37
</td>
38
</tr>
39
40
41
Statement</table>
is short for:
<%</body>
Call Response.write( Time()) %>
42
43 </html>
 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
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
13
Outline
3
4
<html xmlns = "http://www.w3.org/1999/xhtml">
5
6
7
<head>
<title>A Simple ASP Example</title>
HTML generated by
clock.asp
(1 of 2)
8
9
10
<style type = "text/css">
td
color: yellow }
11
12
strong
15
{ font-family: arial, sans-serif;
font-size: 14pt; color: blue }
13
14
{ background-color: black;
p
{ font-size: 14pt }
</style>
16
17
</head>
18
19
<body>
20
 2004 Prentice Hall, Inc.
All rights reserved.
21
<p><strong>A Simple ASP Example</strong></p>
<table border = "6">
22
Outline
<tr>
23
<td>
24
Thursday, May 24, 2001
25
</td>
26
27
HTML generated by
clock.asp
(2 of 2)
<td>
28
2:22:58 PM
29
</td>
30
31
</tr>
32
</table>
33
14
</body>
34
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
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
16
Outline
3
4
<!-- Fig. 33.4 : name.html
-->
5
<!-- XHTML document that request an ASP document -->
6
7
name.html
(1 of 2)
<html xmlns = "http://www.w3.org/1999/xhtml">
8
9
10
11
<head>
<title>Name Request</title>
</head>
12
13
<body>
14
15
16
17
<p style = "font-family: arial, sans-serif">
Enter your name:
</p>
18
 2004 Prentice Hall, Inc.
All rights reserved.
19
<!-- request name.asp when posted -->
20
<form action = "name.asp" method = "post">
17
Outline
21
<input type = "text" name = "namebox" size = "20" />
22
<input type = "submit" name = "submitButton"
action
value = "Enter" />
23
24
</form>
set to ASP file
where information is
posted.
name.html
(2 of 2)
25
26
</body>
27
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
<% @LANGUAGE = VBScript %>
3
<%
4
' Fig. 33.5 : name.asp
5
' Another simple ASP example
6
Option Explicit
7
19
Outline
2
name.asp
(1 of 2)
%>
8
9
10
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
11
12 <html xmlns = "http://www.w3.org/1999/xhtml">
13
14
15
<head>
<title>Name Information</title>
16
17
18
<style type = "text/css">
p
font-size: 14pt; color: navy }
19
20
21
22
{ font-family: arial, sans-serif;
.special { font-size: 20pt; color: green }
</style>
</head>
 2004 Prentice Hall, Inc.
All rights reserved.
23
24
20
<body>
Outline
25
26
<!-- retrieve and display namebox's value -->
27
<p>Hi <% =Request( "namebox" ) %>, </p><br />
28
<p class = "special">Welcome to ASP!</p>
29
30
</body>
Request object retrieves
form data from text field
“namebox”
name.asp
(2 of 2)
31
32 </html>
 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
Description
Allows the programmer to interact with Files, Folders and
Drives.
File
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 disks—computer 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
Methods
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)
 2004 Prentice Hall, Inc. All rights reserved.
26
33.6 File System Objects
Property/method
Property
Description
DateCreated
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.
DateLastAccessed
DateLastModified
Drive
Name
ParentFolder
Path
ShortName
Size
String. The File name.
String. The File’s parent folder name.
String. The File’s path.
String. The File’s name expressed as a short name.
Variant. The size of the File in bytes.
Method
Copy
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.
 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
Description
Properties
Attributes
DateCreated
DateLastAccessed
DateLastModified
Drive
IsRootFolder
Name
ParentFolder
Path
ShortName
ShortPath
Size
Type
Fig. 33.9
Integer. Value indicating Folder’s 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 Folder’s name.
Folder. The Folder’s parent folder.
String. The Folder’s path.
String. The Folder’s name expressed as a short name.
String. The Folder’s path expressed as a short path.
Variant. The total size in bytes of all subfolders and files.
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
Fig. 33.9
Description
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
Description
Variant. The amount of available Drive space in bytes.
DriveLetter
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 0–5, 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 Drive’s path.
RootFolder
Folder object. The Drive’s 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
Description
Properties
AtEndOfLine
AtEndOfStream
Column
Line
Boolean. Indicates whether the end of a line has been encountered.
Boolean. Indicates whether the end of file has been encountered.
Integer. Returns the character’s position in a line.
Integer. Returns the current line number.
Methods
Read
ReadAll
Fig. 33.11
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)
 2004 Prentice Hall, Inc. All rights reserved.
35
33.6 File System Objects
Property/ Method
Description
Methods, cont.
ReadLine
String. Returns one line from the file referenced by the
TextStream object.
String. Writes text to the file referenced by the TextStream object.
Write
WriteBlankLines
WriteLine
Skip
SkipLine
Close
Fig. 33.11
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.
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
<% @LANGUAGE = VBScript %>
3
<% ' Fig. 33.12 : guestbook.asp
4
' Demonstrating File System Objects
5
Option Explicit
6
38
Outline
2
%>
guestbook.asp
(1 of 5)
7
8
9
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
10
11 <html xmlns = "http://www.w3.org/1999/xhtml">
12
13
14
<head>
<title>GuestBook Example</title>
15
16
<style type = "text/css">
17
hr
18
table { text-align: center }
19
td
{ font-size: 12pt }
20
p
{ font-size: 14pt; color: blue }
21
.font { font-family: arial, sans-serif }
22
{ size: 1; color: blue }
</style>
23
</head>
24
<body>
 2004 Prentice Hall, Inc.
All rights reserved.
25 <%
39
Dim fileObject, textFile, guestBook, mailtoUrl
26
27
28
29
30
Outline
Concatenated with file
name guestbook.txt
' get physical path for this ASP page and
Set is required to establish a
' concatenate guestbook.txt to it
variable in VBScript
31
guestbook = Request.ServerVariables(
& "\guestbook.txt"
32
guestbook.asp
Pass Request
method
(2 of 5) server key
"APPL_PHYSICAL_PATH" ) _
ServerVariables
Creating a FSO instance
APPL_PHYSICAL_PATH
assigned to reference
33
' instantiate a FileSystemObject
34
Set fileObject = Server.CreateObject( _
35
fileObject
"Scripting.FileSystemObject" )
36
37
' Check if this request is after the user has posted the form
38
If Request( "hiddenInput" ) = "true" Then
39
40
' Print a thank you
41
Call Response.Write( "Thanks for your entry, " & _
42
Request( "username" ) & "!" )
43 %>
44
<hr />
45 <%
Request object retrieves
hiddenInput value and tests
it against
string “true
Prints
string followed
by ”
users name input in the form
46
' build the mailtoUrl
47
mailtoUrl = Date() & " <a href = " & Chr( 34 ) _
48
&
49
&
Submitted name and email
"mailto:" & Request( "email" ) & Chr( 34 ) _
are combined and assigned to
Pass
value
34 into VBScript
">" & Request( "username" ) & "</a>:
" a mailto
string mailtoUrl
Displays
link.
Date()
assigns:current
Chr” function
to produce double
Request
“email
and
server retrieves
date to beginning
of
quotes (“”)
“username
”
mailtoUrl
 2004 Prentice Hall, Inc.
All rights reserved.
50
40
Outline
51
52
' open the guestbook, 8 is for appending
53
' create the guestbook if it does not exist
54
Set textFile = _
55
fileObject.OpenTextFile( guestbook, 8, True )
56
57
' write data to guestbook.txt
58
Call textFile.WriteLine( "<hr
59
Request( "comment" ) )
60
61
Call textFile.Close()
Method OpenTextFile
retrieves TextStream object
/>"
& mailtoUrl
& _
Contstant
8 indicates
for
accessing
file
append mode
(writing
to
guestbook.txt
the end of the file.)
End If
method
Close()TextStream
method closes
the file
WriteLine writes to
guestbook.txt
62 %>
63
64
guestbook.asp
(3 of 5)
<p>Please leave a message in our guestbook.</p>
65
66
<!-- write form to the client -->
67
<form action = "guestbook.asp" method = "post">
68
<table>
69
<tr>
</td>
Form post action to .asp page
70
<td>Your Name:
71
<td><input class = "font"
72
type = "text" size = "60"
73
name = "username" /></td>
74
</tr>
 2004 Prentice Hall, Inc.
All rights reserved.
75
76
41
<tr>
Outline
77
<td>Your email address:</td>
78
<td><input class = "font"
79
type = "text" size = "60"
80
name = "email"
81
value = "[email protected]" />
83
Form contains two
text fields and text
area for user input
</td>
82
</tr>
84
85
guestbook.asp
(4 of 5)
<tr>
86
<td>Tell the world:
</td>
87
<td><textarea name = "comment" rows = "3"
88
cols = "50">
89 Replace this text with the information
90 you would like to post.</textarea></td>
91
</tr>
92
</table>
Passes parameter
hiddenInput
value “true”
93
94
<input type = "submit" value = "submit" />
95
<input type = "reset" value = "clear" />
96
<input type = "hidden" name = "hiddenInput"
value = "true" />
97
98
</form>
99
 2004 Prentice Hall, Inc.
All rights reserved.
100 <%
42
101
' check if the file exists
102
If fileObject.FileExists( guestBook ) = True Then
103
104
105
106
Outline
FSO object FileExists
checks if guestbook.txt
' open the guestbook, "1" is for reading
exists.
Set textFile = fileObject.OpenTextFile( guestbook, 1 )
guestbook.asp
(5 of 5)
107
108
' read the entries from the file and write them to
109
' the client.
110
Call Response.Write( "Guestbook Entries:<br />" & _
textFile.ReadAll() )
111
112
Call textFile.Close()
TextStream and ReadAll
113
114
End If
115 %>
116
117
</body>
118
Read entries
from
methods
read entire
guestbook.txt
contents
ofand write writes
Response.Write
guestbook.txt
XHTML
to the
text
to client
client. Contains
XHTML markup rendered
on client browser.
119 </html>
 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
<hr />5/24/2001 <a href = "mailto:[email protected]">tem</a>:
ASP is a great tool
for server-side development.
2
<hr />5/24/2001 <a href = "mailto:[email protected]">dan</a>:
ASP is my
45
Outline
preferred server-side development tool.
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
Client’s DNS name or IP address.
REQUEST_METHOD
Request method (i.e., get and post).
SERVER_NAME
Server’s 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
<% @LANGUAGE = VBScript %>
3
<%
4
' Fig. 33.15 : instantpage.asp
5
' ASP document that posts data to process.asp
6
Option Explicit
7
50
Outline
2
instantpage.asp
(1 of 4)
%>
8
9
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
10
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
11
12 <html xmlns = "http://www.w3.org/1999/xhtml">
13
14
15
<head>
<title>Instant Page Content Builder</title>
16
17
18
<style type = "text/css">
table { text-align: center;
19
font-size: 12pt;
20
color: blue;
21
font-size: 12pt;
22
font-family: arial, sans-serif }
23
</style>
24
25
</head>
 2004 Prentice Hall, Inc.
All rights reserved.
26
27
51
<body>
Server-side include
Outline
28
29
<!-- include the header
-->
30
<!-- #include virtual = "/includes/header.shtml" -->
31
<h2>Instant Page Content Builder</h2>
instantpage.asp
(2 of 4)
32
33 <% ' if process.asp posted an error, print the error
34
' message.
35
If Session( "errormessage" ) <> "no error" Then
36
Call Response.Write( Session( "errorMessage" ) )
37
' otherwise, print the welcome back message, if any
38
Else
39
40
41
42 %>
43
44
45
46
47
48
Call
End If
First time page is executed,
Session object
Response.Write(
Session( "welcomeBack"
)retrieves
)
line value
35 returns true
variable
errorMessage
session
If true, errorMessage
variable used for error
value iswelcomeBack
written to client
session
errorMessage never
has a
variable
displays
value
unless
errors are
<!-- a form Else,
to get
the information
from
the user -->
WelcomeBack
value
is“welcome
encounteredback” message
<form action
= "process.asp"
method = "post">
written
to the client
to returning users
messages
<table>
If statement tests
errorMessage equality
to “no error”. Return
True or False.
<tr>
<td>Your Name:
</td>
Requests process.asp when
form is posted
 2004 Prentice Hall, Inc.
All rights reserved.
49
<td><input type = "text" size = "60"
50
name = "username" /></td>
51
52
Outline
</tr>
52
53
54
<tr>
<td>Enter the Filename:</td>
instantpage.asp
(3 of 4)
55
56
<td><input type = "text" size = "60"
57
name = "filename"
58
value = "yourfilename" /></td>
59
</tr>
60
61
62
<tr>
<td>Enter the Title:</td>
63
64
<td><input type = "text" size = "60"
65
name = "doctitle"
66
value = "document title" /></td>
67
</tr>
68
69
70
<tr>
<td>Enter the content:</td>
71
72
<td><textarea name = "content" rows = "3"
 2004 Prentice Hall, Inc.
All rights reserved.
cols = "50">
73
74 Replace this text with the
75 information you would like to post.</textarea></td>
76
</tr>
77
</table>
78
79
Server-side
include
<input type
= "submit"
value = "submit" />
80
<input type = "reset" value = "clear" />
81
53
Outline
instantpage.asp
(4 of 4)
</form>
82
83
84
<!-- #include virtual = "/includes/footer.shtml" -->
</body>
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
<!-- Fig. 33.16: header.shtml
-->
2
<!-- Server-side include file containing XHTML -->
3
<hr style = "color: blue" />
4
<img height = "100" src = "/images/bug2bug.gif" alt = "Bug" />
5
<hr style = "color: blue" />
57
Outline
header.shtml
(1 of 1)
 2004 Prentice Hall, Inc.
All rights reserved.
1
<!-- Fig. 33.17: footer.shtml
2
<!-- Server-side include file containing XHTML -->
3
<hr style = "color: blue" />
4
<a style = "text-align: center"
5
6
7
8
-->
href = "mailto:orders">ordering information</a> -
58
Outline
footer.shtml
<a style = "text-align: center"
href = "mailto:editor">contact the editor</a><br />
<hr style = "color: blue" />
server-side include file
for the document footer
 2004 Prentice Hall, Inc.
All rights reserved.
1
<% @LANGUAGE = VBScript %>
59
Outline
2
3
<%
4
' Fig. 33.18 : process.asp
5
' ASP document that creates user's ASP document
6
Option Explicit
7
%>
8
9
10
11
12
13
<%
process.asp
(1 of 6)
If field is empty or
contains default string
yourfilename, lines 19Dim message,
q
21 assign
XHTML error
message to variable
Iftostatement
validates
q = Chr( 34
) ' assign quote character
q
message.
Session( "errorMessage" ) = "no error"contents of text field.
14
15
' check to make sure that they have entered a
16
' valid filename
17
If ( LCase( Request( "filename" ) ) = "yourfilename" ) _Assign
message value to
18
Or Request( "filename" ) = "" Then
session variable
19
message = "<p style = " & q & "color: red" & q & _
errorMessage
20
">" & "Please enter a valid name or filename.</p>"
21
Session( "errorMessage" ) = message
22
Call Server.Transfer( "instantpage.asp" )
23
24
25
End If
Server method
Transfer requests
Dim directoryPath, filePath, fileObject, fileName
instantpage.asp
 2004 Prentice Hall, Inc.
All rights reserved.
26
60
27
' Create a FileSystem Object
28
Request.ServerVariables
Set fileObject = Server.CreateObject(
_
29
retrieves)physical
"Scripting.FileSystemObject"
path
30
31
32
directoryPath = _
Request.ServerVariables( "APPL_PHYSICAL_PATH" )
33
34
fileName = Request( "filename" ) & ".asp"
35
36
' build path for text file
37
filePath = directoryPath & "\" & fileName
38
39
' check if the file already exists
40
If fileObject.FileExists( filePath ) Then
41
If file exists, variable
errorMessage value is set to
XHTML containing error message
message = "<p style = " & q & "color: red" & q & _
42
">" & "The file name is in use.<br />" & _
43
"Please use a different file name.</p>"
filePath
44
Session( "errorMessage" ) = message
method.
45
Call Server.Transfer( "instantpage.asp" )
46
FSO object is created if valid Outline
user
name is entered and assigned
Builds fileName by
reference fileObject
concatenating
process.asp
“filename” to the(2.asp
of 6)
file extension
Specify server path where
ASP file is written
passed FileExists
Determines if file exists.
End If
47
Server.Transfer method
requests instantpage.asp
 2004 Prentice Hall, Inc.
All rights reserved.
48
' save XHTML for the welcome back message
49
' in a session variable
50
message = "<p style = " & q & "color: blue" & q & _
51
">" & "Welcome Back, " & Request( "username" ) & _
52
"</p><br />"
53
Session( "welcomeBack" ) = message
61
Outline
process.asp
(3 of 6)
54
55
Dim header, footer, textFile, openMark, closeMark
56
openMark = "<" & "%"
57
closeMark = "%" & ">"
58
59
60
61
62
Construct XHTML for header
Assigns XHTML for “welcome
' build the header.
back” message to welcomeBack
Assign
ASP
scripting
' vbCrLf inserts a carriage return/linefeed into
the text
session
variable
delimiters
to
string
variables
' string which makes the XHTML code more readable
openMark and closeMark
header = openMark & " @LANGUAGE = VBScript " & closeMark _
63
& vbCrLf & openMark & " ' " & fileName _
64
& " " & closeMark & vbCrLf & vbCrLf _
65
& "<!DOC" & "TYPE html PUBLIC " & q & _
66
"-//W3C//DTD XHTML 1.0 Transitional//EN" & q & _
67
vbCrLf & q & "http://www.w3.org/TR/xhtml1/" & _
68
"DTD/xhtml1-transitional.dtd" & q & ">" & vbCrLf & _
69
"<html xmlns = " & q & "http://www.w3.org/1999/xhtml" & _
70
q & ">" & vbCrLf & "<head>" & vbCrLf _
71
& "<meta name = " & q & "author" & q & " content = " _
72
& q & Request( "username" ) & q & " />" & vbCrLf _
73
& "<meta name = " & q & "pubdate" & q & " content = " _
 2004 Prentice Hall, Inc.
All rights reserved.
74
& q & Date() & q & " />" & vbCrLf _
75
& "<title>" & Request( "doctitle" ) & "</title>" _
76
& vbCrLf & "</head>" & vbCrLf & "<body>" & vbCrLf _
77
& "<!-- #" & "include " & "virtual = " & _
78
"/includes/header.shtml -->" _
79
& vbCrLf & "<h2 style = " & q & "text-align: center" & _
80
footer
q & "><em>" & Request( "doctitle" ) & "</em></h2>"
& _variable
81
vbCrLf & "<br />" & vbCrLf
62
Outline
process.asp
(4 of 6)
assigned
to XHTML footer contents
82
83
' build the footer using a different style for
84
' building the string
85
footer = vbCrLf & "<br /><br /><br />" & vbCrLf & _
86
"You have requested this page on " & _
87
openMark & " =Date() " & closeMark & "," & _
88
vbCrLf & "at " & openMark & " =Time() " & _
89
closeMark & "." & vbCrLf & _
90
"<!-- #" & "include " & "virtual = " & _
91
"/includes/footer.shtml -->" _
92
& vbCrLf & vbCrLf & "</body>" & vbCrLf & "</html>"
Form values retrieved
using Request object
93
 2004 Prentice Hall, Inc.
All rights reserved.
94
' create the ASP file
95
Set textFile = fileObject.CreateTextFile( filePath, False )
96
With textFile
63
Outline
Call .WriteLine( header & Request( "content" ) & _
97
footer )
98
Lines
Call .Close()
99
103-129 send XHTML to
client that contains link to
created page
End With
100
101 %>
process.asp
(5 of 6)
102
103 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
104
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
105
106 <html xmlns = "http://www.w3.org/1999/xhtml">
107
108
<head>
109
<!-- use the title given by the user -->
110
<title>File Generated: <% =fileName %></title>
111
112
113
<style type = "text/css">
h2 { font-family: arial, sans-serif;
text-align: center }
114
115
</style>
116
117
</head>
118
 2004 Prentice Hall, Inc.
All rights reserved.
119
<body>
64
120
<!-- #include virtual = "/includes/header.shtml" -->
121
<h2><em>File <% =fileName %>
was created successfully.</em>
122
123
</h2><br />
124
125
<!-- provide a link to the generated page -->
126
<a href = "<% =fileName %>">View your file</a>
127
<!-- #include virtual = "/includes/footer.shtml" -->
128
Outline
process.asp
(6 of 6)
</body>
129 </html>
 2004 Prentice Hall, Inc.
All rights reserved.
1
<% @LANGUAGE = VBScript %>
2
<% ' aboutme.asp %>
65
Outline
3
4
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
5
"http://www.w3c.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
6
7
<html xmlns = "http://www.w3.org/1999/xhtml">
aboutme.asp
(1 of 2)
<head>
8
<meta name = "author" content = "tem" />
9
<meta name = "pubdate" content = "2/27/2001" />
10
<title>About Me</title>
11
</head>
12
<body>
13
<!-- Fig. 33.16: header.shtml
14
<!-- Server-side include file containing XHTML -->
-->
15
<hr style = "color: blue" />
16
<img height = "100" src = "/images/bug2bug.gif" alt = "Bug" />
17
<hr style = "color: blue" />
18
<h2 style = "text-align: center"><em>About Me</em></h2>
19
<br />
20 This page contains lots of exciting and interesting information about me!
21
<br /><br /><br />
22 You have requested this page on 10/15/2003,
23 at 11:45:47 AM.
24
<!-- Fig. 33.17: footer.shtml
-->
25
<!-- Server-side include file containing XHTML -->
 2004 Prentice Hall, Inc.
All rights reserved.
26
<hr style = "color: blue" />
27
<a style = "text-align: center"
href = "mailto:orders">ordering information</a> -
28
29
Outline
<a style = "text-align: center"
href = "mailto:editor">contact the editor</a><br />
30
31
66
<hr style = "color: blue" />
aboutme.asp
(2 of 2)
32
33
</body>
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 Microsoft’s UDA architecture.
Application or Browser
ADO
OLE DB
ODBC
Relational data sources
 2004 Prentice Hall, Inc. All rights reserved.
Non-relational data sources
Legacy data
71
33.8 ActiveX Data Objects (ADO)
Fig. 33.23 Portion of the ADO object model.
Connection
Command
Parameters
Errors
Error
RecordSet
Fields
 2004 Prentice Hall, Inc. All rights reserved.
Parameter
Field
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
Fig. 33.24
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.
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
<% @LANGUAGE = VBScript %>
75
Outline
2
3
<%
4
' Fig. 33.25 : database.asp
5
' ASP document for interacting with the database
6
Option Explicit
7
8
9
10
11
12
13
14
15
16
17
18
database.asp
(1 of 2)
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
session
Method Openrecord
opensor EOF if no
On Error Resume Next
variablewere found
records
Session( "errorString" ) = ""
database specified
by
errorString
ODBC System DSN
loginData(login
reference
Set connection = Server.CreateObject(
"ADODB.Connection"
)
) is seterrorHandlerLog
processes
errors
to
an
ADODB.recordset
Call connection.Open( "login" )
Open method is passed string
Call errorHandlerLog()object
containing SQL query and
ADODB.Connection object
errorHandlerLog
' create the record set
called again
19
Set loginData = Server.CreateObject( "ADODB.Recordset" )
20
Call loginData.Open( Session( "query" ), connection )
21
Set Session( "loginData" ) = loginData
22
23
24
Call errorHandlerLog()
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
Sub errorHandlerLog()
76
If Err.Number <> 0 Then
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
37 %>
 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
<% @LANGUAGE = VBScript %>
3
78
Outline
2
<%
4
' Fig. 33.27 : login.asp
5
' ASP document to login to instantpage.asp
6
Option Explicit
login.asp
(1 of 7)
7
8
' create the SQL query
9
Session( "query" ) = "SELECT loginID FROM Users"
10
Call Server.Execute( "database.asp" )
11 %>
12
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
13 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
14
15
16 <html xmlns = "http://www.w3.org/1999/xhtml">
17
18
19
<head>
<title>Login Page</title>
20
21
22
<style type = "text/css">
table { text-align: center;
23
font-size: 12pt;
24
color: blue;
25
font-size: 12pt;
 2004 Prentice Hall, Inc.
All rights reserved.
font-family: arial, sans-serif }
26
27
28
.error { color: red }
79
Outline
</style>
29
30
login.asp
(2 of 7)
</head>
31
32
<body>
33
34
<!-- #include virtual="/includes/header.shtml" -->
35 <%
36
If Session( "errorString" ) = "" Then
37
' if this is a return after a failed attempt,
38
' print an error
39
If Session( "loginFailure" ) = True Then %>
40
<p class = "error">Login attempt failed,
Tests
please try again</p>
41
42 <%
if session variable
errorString value is
empty string
End If
43
44
' begin the form %>
45
<p>Please select your name and enter
46
your password to login:</p><br />
47
Lines 39-41 test is session variable
loginFailure is True
 2004 Prentice Hall, Inc.
All rights reserved.
48
<form action = "submitlogin.asp" method = "post">
80
Outline
49
50
<!-- format the form using a table -->
51
<table border = "0">
<tr>
52
<td>Name:</td>
53
54
select structure builds dropdown list of loginIDs
login.asp
(3 of 7)
<td>
55
<select name = "loginID">
56
<option value = "noSelection">
57
Requests loginID
Select your name</option>
58
cookie
59
60 <%
61
62
63
64
65
If Request.Cookies( "loginID" ) <> "" Then
Call BuildReturning()
Else
Call BuildNewUser()
Selects the returning user’s
login ID option
Build loginID options
End If
66 %>
</select>
67
68
69
</td>
</tr>
70
 2004 Prentice Hall, Inc.
All rights reserved.
<tr>
71
81
72
<td>Password:</td>
73
<td><input type = "password"
name = "password" /></td>
74
login.asp
(4 of 7)
</tr>
75
76
<tr>
77
78
<td></td>
79
<td align = "left">
<input type = "submit" value = "Log Me In" />
80
</td>
81
82
</tr>
83
</table>
84
Outline
</form>
85
86
<!-- #include virtual="/includes/footer.shtml" -->
87 <%
88
89
90
Else
Call Response.Write( Session( "errorString" ) )
End If
If false, print error
message to user
91 %>
92
</body>
93 </html>
94
 2004 Prentice Hall, Inc.
All rights reserved.
95 <%
82
96
' builds the option items for loginIDs and writes
97
' selected for the loginID of the returning user
98
Sub BuildReturning()
99
Outline
login.asp
(5 of 7)
Dim found, loginData
100
101
Set loginData = Session( "loginData" )
102
103
' pull user names from the record set to populate the
104
' dropdown list
105
found = False
106
107
Tests for EOF
While Not loginData.EOF
108
' create this record's dropdown entry
109 %>
<option
110 <%
' if we did not write selected for
111
' before
112
If ( Not found ) Then
set totests
False
Iffound
statement
whether
before needs
loop to be
option
any option
selected
113
114
' if the current record's loginID is equal to
115
' the loginID cookie, then it is the loginID of
116
' the returning user, and thus we need to write
117
' selected for this option; in this case we also
118
' need to signal that we have written selected
119
' for an option by setting found to True.
 2004 Prentice Hall, Inc.
All rights reserved.
If Request.Cookies( "loginID" ) _
120
= loginData( "loginID" ) Then
121
Call Response.Write( "selected = " & _
122
Chr( 34 ) & "selected" & Chr( 34 ) )
123
found = True
124
127 %>
128
129 <%
Outline
If statement writes
selected for an
option
End If
125
126
83
Once selected is
Determines whether
current
written
for an option,
value = "<% =loginData( "loginID" ) %>">
record’s loginID field is
found set to true
<% =loginData( "loginID" ) %></option>
equal to loginID cookie
login.asp
(6 of 7)
End If
Call loginData.MoveNext()
130
Wend
131
End Sub
132
 2004 Prentice Hall, Inc.
All rights reserved.
133
' builds the option items for loginIDs without writing
134
' selected for any loginID
135
Sub BuildNewUser()
136
Dim loginData
Outline
login.asp
(7 of 7)
137
138
84
Set loginData = Session( "loginData" )
139
140
' pull user names from the record set to populate the
Increments
141
' dropdown list
142
While Not loginData.EOF
the record set pointer
to next record
143
' create this record's dropdown entry
144 %>
<option value = "<% =loginData( "loginID" ) %>">
145
<% =loginData( "loginID" ) %></option>
146 <%
Call loginData.MoveNext()
147
Wend
148
End Sub
149 %>
Writes option display as
while loop (lines
iterates
current107-130)
login ID
through loginData’s 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
<% @LANGUAGE = VBScript %>
87
2
3
Check whether
<% ' Fig. 33.28 : submitlogin.asp
Outline
password
4
field
is empty
or idand password
' ASP document to check
user's
username
5
Option Explicit
6
loginID field contains
submitlogin.asp
default value
(1 of 2)
If so, variable
7
' test if a user name and a password were
8
' entered. If not, transfer back to the login page.
9
If Request( "password" ) = "" Or _
10
Request( "loginID" ) = "noSelection"
11
Session( "loginFailure" ) = True
12
Call Server.Transfer( "login.asp" )
13
End If
14
15
loginFailure set to
true, client redirected
back to login.asp
Then
Checks password against
the
WHERE specifies
a
password in recordset
condition on which records
are selected
Dim connection, loginData
16
17
' create the SQL query
18
Session( "query" ) = _
19
"SELECT * FROM Users WHERE loginID = '" & _
20
Request( "loginID" ) & "'"
21
22
Call Server.Execute( "database.asp" )
23
Set loginData = Session( "loginData" )
Sets
reference
loginData to
Executes
database.asp
to
session
variable loginData
query database
(contains records matching
query.)
24
 2004 Prentice Hall, Inc.
All rights reserved.
25
26
If Request( "password" ) = loginData( "password" ) Then
Sets cookie’s expiration date to
current date plus 3 days
27
' password is OK, adjust loginFailure
28
Session( "loginFailure" ) = False
29
88
Outline
Sets session variable
If true, line writes form’s loginID
loginFailure value
submitlogin.asp
value as cookie named loginID
to False
30
' write a cookie to recognize them the next time they
31
' go to login.asp
32
Response.Cookies( "loginID" ) = Request( "loginID" )
(2 of 2)
33
34
' give it three days to expire
35
Response.Cookies( "loginID" ).Expires = Date() + 3
Calls Server method Transfer to
redirect client to instantpage.asp
36
37
' send them
to instantpage.asp
Otherwise
loginFailure
38
Call
39
set to True
Server.Transfer(
)
and client is "instantpage.asp"
redirected to login.asp
Else
40
Session( "loginFailure" ) = True
41
Call Server.Transfer( "login.asp" )
42
End If
43 %>
 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
Component name
Description
MSWC.BrowserType
ActiveX component for gathering information about the
client’s 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 server’s 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.
 2004 Prentice Hall, Inc. All rights reserved.
1
<% @LANGUAGE = VBScript %>
3
<%
4
' Fig. 33.31 : component.asp
5
' Demonstrating Server-side ActiveX Components
6
Option Explicit
7
94
Outline
2
component.asp
(1 of 4)
%>
8
9
10
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
11
12 <html xmlns = "http://www.w3.org/1999/xhtml">
13
14
15
16
<head>
<title>ActiveX Component Example</title>
</head>
17
18
<body>
19
20
21
22
<strong style = "font-family: arial, sans-serif">
Server-side ActiveX Components
</strong>
23
24
<p>
 2004 Prentice Hall, Inc.
All rights reserved.
25 <%
26
95
Dim rotator, browser, information, counter
27
Outline
Sends advertisement as HTML to client. Method
GetAdvertisement called using reference rotator.
rotator = Server.CreateObject( "MSWC.AdRotator" )
Retrieves advertisements from config.txt
28
' create an AdRotator object
29
Set
30
31
' use config.txt to send an advertisement to theCreates
client
32
Call Response.Write( _
33
component.asp
(2 of 4)
AdRotator component instance,
assigns it reference rotator
rotator.GetAdvertisement( "config.txt" ) )
34
35
' create a BrowserType object
36
Set browser = Server.CreateObject( "MSWC.BrowserType" )
37
38
If browser.VBScript = True Then
Obtains information about user’s browser
39 %>
40
<script language = "VBScript">
Call Msgbox( "Client browser supports VBScript!" )
41
42
</script>
Check property VBScript value
43 <%
44
End If
45
46
If browser.JavaScript = True Then
47 %>
48
49
50
<script language = "JavaScript">
alert( "Client browser supports JavaScript!" );
</script>
Test JavaScript property
 2004 Prentice Hall, Inc.
All rights reserved.
51 <%
52
96
End If
53
Outline
BrowserType object’s Browser,
Version and MinorVer properties
54
' get client's browser information
55
information = "<p>Your browser information is:<br />" & _
can obtain similar client information
56
Request.ServerVariables( "HTTP_USER_AGENT" ) & _
57
"<br />Browser: " & browser.Browser & " Version: " & _
58
browser.Version & " Minor version: " & _
59
browser.MinorVer & "<br />Cookies are "
Passes server variable
key
component.asp
HTTP_USER_AGENT(3
toof 4)
ServerVariables, obtains string
containing user information
60
61
62
63
64
65
66
67
If browser.Cookies Then
information = information & "enabled</p><br />"
Else
information = information & "disabled</p><br />"
End If
Tests Cookies property to determine if
browser supports cookies
Call Response.Write( information )
68
69
' create Page Counter Object
70
Set counter = Server.CreateObject( "MSWC.PageCounter" )
71
Call counter.PageHit()
' page has been "hit"
72 %>
Increments number of “hits” by one
 2004 Prentice Hall, Inc.
All rights reserved.
73
</p>
Returns number of “hits”
74
75
<p style = "color: blue; font-size: 12pt">
76
This page has been visited <% =counter.Hits() %>
77
times!</p>
78
</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
REDIRECT redirect.asp
2
width 54
3
height 36
4
border 1
5
*
6
/images/us.gif
7
http://www.odci.gov/cia/publications/factbook/geos/us.html
8
United States Information
9
20
101
Header contains
REDIRECT file URL
Image
URL, destination
URL,
Advertisement
dimensions
Asterisk
separates
alt value,
imageheader
display ratio
from advertisements
Outline
config.txt
(1 of 1)
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
<% @LANGUAGE = VBScript %>
3
102
Outline
2
<%
4
' Fig. 33.33 : redirect.asp
5
' Redirection Page for AdRotator Component
6
Option Explicit
redirect.asp
(1 of 1)
7
Call Response.Redirect( Request( "url" ) )
8
9
%>
 2004 Prentice Hall, Inc.
All rights reserved.