Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 25 - Active Server Pages (ASP)

Similar presentations


Presentation on theme: "Chapter 25 - Active Server Pages (ASP)"— Presentation transcript:

1 Chapter 25 - Active Server Pages (ASP)
Outline Introduction How Active Server Pages Work Setup Active Server Page Objects Simple ASP Examples File System Objects Session Tracking and Cookies Accessing a Database from an Active Server Page Server-Side ActiveX Components Internet and World Wide Web Resources

2 Server-side technologies
25.1 Introduction Server-side technologies Dynamically creates Web pages Uses client information, server information and information from the Internet Active Server Pages (ASP) Microsoft Server-side technology Dynamically builds documents in response to client requests Delivers dynamic Web content XHTML, DHTML, ActiveX controls, client-side scripts and Java applets

3 25.2 How Active Server Pages Work
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

4 25.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)

5 25.3 Setup Web Server Need to run Web server to use Active Server Pages IIS (Internet Information Services) or PWS 4.0 (Personal Web Server 4.0) Create a virtual directory Copy files to c:\InetPub\Wwwroot or c:\Webshare\Wwwroot

6 25.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 inforamtion to client XHTML, text Server Access to server methods or properties

7 25.4 Active Server Page Objects

8 Processing directive specifying scripting language
1 = VBScript %> 2 3 <% ' Fig : clock.asp ' A simple ASP example Option Explicit 7 %> 8 9 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 10 " 11 12 <html xmlns = " 13 <head> <title>A Simple ASP Example</title> 16 <style type = "text/css"> td { background-color: black; color: yellow } strong { font-family: arial, sans-serif; font-size: 14pt; color: blue } p { font-size: 14pt } </style> 24 </head> 26 <body> 28 <p><strong>A Simple ASP Example</strong></p> <table border = "6"> <tr> <td> <% =FormatDateTime( Now, vbLongDate ) %> </td> 35 Processing directive specifying scripting language Scripting delimeter wraps around code executed on the server. Clock.asp sends Web server’s date and time to the client as XHTML markup <% %> scripting delimeter @LANGUAGE processing directive Option Explicit FormatDateTime Now vbLongDate format Response.write Time Requires programmer explicitly define all variables Returns server date and time (Now) as a string formatted in vbLongDate format “<%=“ is short for Response.write

9 Clock.asp Time Program Output
<td> <% =Time() %> </td> </tr> </table> </body> 42 43 </html> Statement is short for: <% Call Response.write( Time()) %> Clock.asp Time Program Output

10 Fig. 25.3 XHTML generated by clock.asp.
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 2 " 3 4 <html xmlns = " 5 <head> <title>A Simple ASP Example</title> 8 <style type = "text/css"> td { background-color: black; color: yellow } strong { font-family: arial, sans-serif; font-size: 14pt; color: blue } p { font-size: 14pt } </style> 16 </head> 18 <body> 20 <p><strong>A Simple ASP Example</strong></p> <table border = "6"> <tr> <td> Thursday, May 24, 2001 </td> 27 <td> :22:58 PM </td> </tr> </table> </body> 34 35 </html> Fig XHTML generated by clock.asp.

11 25.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

12 action set to ASP file where information is posted.
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 2 " 3 4 <!-- Fig : name.html > 5 <!-- XHTML document that request an ASP document --> 6 7 <html xmlns = " 8 <head> <title>Name Request</title> </head> 12 <body> 14 <p style = "font-family: arial, sans-serif"> Enter your name: </p> 18 <!-- request name.asp when posted --> <form action = "name.asp" method = "post"> <input type = "text" name = "namebox" size = "20" /> <input type = "submit" name = "submitButton" value = "Enter" /> </form> 25 </body> 27 28 </html> Name.html passes information into an ASP document using the post method. action set to ASP file where information is posted.

13 Name.html Program Output

14 Request object retrieves form data from textfield “namebox”
1 = VBScript %> 2 3 <% ' Fig : name.asp ' Another simple ASP example Option Explicit 7 %> 8 9 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 10 " 11 12 <html xmlns = " 13 <head> <title>Name Information</title> 16 <style type = "text/css"> p { font-family: arial, sans-serif; font-size: 14pt; color: navy } special { font-size: 20pt; color: green } </style> </head> 23 <body> 25 <!-- retrieve and display namebox's value --> <p>Hi <% =Request( "namebox" ) %>, </p><br /> <p class = "special">Welcome to ASP!</p> 29 </body> 31 32 </html> Name.asp Uses the Request method to retrieve the data posted in Name.html. Places this data within XHTML tags for output. Request object retrieves form data from textfield “namebox”

15 Name.asp Program Output

16 File System Objects (FSOs)
Allow programmer to manipulate files, directories and drives Read and write text Microsoft Sctipting Runtime Library (Fig 25.6) FileSystemObject, File, Folder, Drive and TextStream Use to create directories, move files, determine whether a Drive exists FileSystemObject methods (Fig. 25.7) File object Allows programmer to gather info about files, manipulate files, open files File properties and methods (Fig. 25.8)

17 25.6 File System Objects

18 25.6 File System Objects

19 25.6 File System Objects

20 25.6 File System Objects

21 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. 25.9)

22 25.6 File System Objects

23 25.6 File System Objects

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

25 File System Objects (FSOs)
Drive object (Fig ) Gather information about drives Property DriveLetter Contains drive letter Property SerialNumber Contains drive serial number Property FreeSpace Contains number of available bytes

26 25.6 File System Objects

27 File System Objects (FSOs)
TextStream object (Fig ) Manipulate text files

28 25.6 File System Objects

29 25.6 File System Objects

30 25.6 File System Objects

31 Set is required to establish a variable in VBScript
1 = VBScript %> 2 3 <% ' Fig : guestbook.asp ' Demonstrating File System Objects Option Explicit 6 %> 7 8 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 9 " 10 11 <html xmlns = " 12 <head> <title>GuestBook Example</title> 15 <style type = "text/css"> hr { size: 1; color: blue } table { text-align: center } td { font-size: 12pt } p { font-size: 14pt; color: blue } font { font-family: arial, sans-serif } </style> </head> <body> 25 <% Dim fileObject, textFile, guestBook, mailtoUrl 27 ' get physical path for this ASP page and ' concatenate guestbook.txt to it guestbook = Request.ServerVariables( "APPL_PHYSICAL_PATH" ) _ & "\guestbook.txt" 32 ' instantiate a FileSystemObject Set fileObject = Server.CreateObject( _ "Scripting.FileSystemObject" ) Guestbook.asp Users enter name, address and comments. FSOs write this data to a server file. Request ServerVariables APPL_PHYSICAL_PATH fileObject Set is required to establish a variable in VBScript Pass Request method ServerVariables server key APPL_PHYSICAL_PATH Concatenated with file name guestbook.txt Creating a FSO instance assigned to reference fileObject

32 Lines 41-60 execute when pages is loaded with post request.
36 ' Check if this request is after the user has posted the form If Request( "hiddenInput" ) = "true" Then 39 ' Print a thank you Call Response.Write( "Thanks for your entry, " & _ Request( "username" ) & "!" ) 43 %> <hr /> 45 <% ' build the mailtoUrl mailtoUrl = Date() & " <a href = " & Chr( 34 ) _ & "mailto:" & Request( " " ) & Chr( 34 ) _ & ">" & Request( "username" ) & "</a>: " 50 51 ' open the guestbook, 8 is for appending ' create the guestbook if it does not exist Set textFile = _ fileObject.OpenTextFile( guestbook, 8, True ) 56 ' write data to guestbook.txt Call textFile.WriteLine( "<hr />" & mailtoUrl & _ Request( "comment" ) ) Call textFile.Close() End If 62 %> 63 <p>Please leave a message in our guestbook.</p> 65 Request object retrieves hiddenInput value and tests it against string “true” Guestbook.asp Users enter name, address and comments. FSOs write this data to a server file. Request mailtoUrl Date() 34 “” WriteLine Close() Append Mode Lines execute when pages is loaded with post request. Prints string followed by users name input in the form Date() assigns current server date to beginning of mailtoUrl Sumbitted name and are combined and assigned to sring mailtoUrl Pass value 34 into VBScript Chr function to produce double quotes (“”) Displays a mailto: link. Request retrieves “ ” and “username” Contstant 8 indicates append mode (writing to the end of the file.) Method OpenTextFile retrieves TextStream object for accessing file guestbook.txt TextStream method WriteLine writes to guestbook.txt Close() method closes the file

33 Form post action to .asp page
<!-- write form to the client --> <form action = "guestbook.asp" method = "post"> <table> <tr> <td>Your Name: </td> <td><input class = "font" type = "text" size = "60" name = "username" /></td> </tr> 75 <tr> <td>Your address:</td> <td><input class = "font" type = "text" size = "60" name = " " value = /> </td> </tr> 84 <tr> <td>Tell the world: </td> <td><textarea name = "comment" rows = "3" cols = "50"> 89 Replace this text with the information 90 you would like to post.</textarea></td> </tr> </table> 93 <input type = "submit" value = "submit" /> <input type = "reset" value = "clear" /> <input type = "hidden" name = "hiddenInput" value = "true" /> </form> 99 Form post action to .asp page Guestbook.asp Users enter name, address and comments. FSOs write this data to a server file. <form> post action hiddenInput Form contains two text fields and text area for user input Passes parameter hiddenInput value “true”

34 Lines 100-115 execute every time the client requests this ASP page
100 <% ' check if the file exists If fileObject.FileExists( guestBook ) = True Then 103 104 ' open the guestbook, "1" is for reading Set textFile = fileObject.OpenTextFile( guestbook, 1 ) 107 ' read the entries from the file and write them to ' the client. Call Response.Write( "Guestbook Entries:<br />" & _ textFile.ReadAll() ) Call textFile.Close() 113 End If 115 %> 116 </body> 118 119 </html> Lines execute every time the client requests this ASP page FSO object FileExists checks if guestbook.txt exists. Guestbook.asp Users enter name, address and comments. FSOs write this data to a server file. FileExists() TextStream() ReadAll() Response.Write Response.Write writes text to client. Contains XHTML markup rendered on client browser. TextStream and ReadAll methods read entire contents of guestbook.txt Read entries from guestbook.txt and write XHTML to the client

35 Program Output

36 Program Output

37 XHTML generated by guestbook.asp
1 <hr />5/24/2001 <a href = ASP is a great tool for server-side development. 2 <hr />5/24/2001 <a href = ASP is my preferred server-side development tool. XHTML generated by guestbook.asp

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

39 25.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

40 25.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 <% %> delimeters

41 1 <% @LANGUAGE = VBScript %>
2 3 <% ' Fig : instantpage.asp ' ASP document that posts data to process.asp Option Explicit 7 %> 8 9 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 10 " 11 12 <html xmlns = " 13 <head> <title>Instant Page Content Builder</title> 16 <style type = "text/css"> table { text-align: center; font-size: 12pt; color: blue; font-size: 12pt; font-family: arial, sans-serif } </style> 24 </head> 26 <body> 28 <!-- include the header > <!-- #include virtual = "/includes/header.shtml" --> <h2>Instant Page Content Builder</h2> 32 Instantpage.asp Recieves error message from process.asp Uses server side include to create dynamic content (embedded file) Server-side include

42 Session object retrieves variable value
33 <% ' if process.asp posted an error, print the error ' message. If Session( "errormessage" ) <> "no error" Then Call Response.Write( Session( "errorMessage" ) ) ' otherwise, print the welcome back message, if any Else Call Response.Write( Session( "welcomeBack" ) ) End If 41 42 %> <!-- a form to get the information from the user --> <form action = "process.asp" method = "post"> <table> <tr> <td>Your Name: </td> 48 <td><input type = "text" size = "60" name = "username" /></td> </tr> 52 <tr> <td>Enter the Filename:</td> 55 <td><input type = "text" size = "60" name = "filename" value = "yourfilename" /></td> </tr> 60 <tr> <td>Enter the Title:</td> 63 <td><input type = "text" size = "60" name = "doctitle" value = "document title" /></td> </tr> If statement tests errorMessage equality to “no error”. Return True or False. Session object retrieves variable value errorMessage never has a value unless errors are encountered First time page is executed, line 35 returns true Instantpage.asp session variable with no explicit value contains an empty string When line 36 is executed and errorMessage has no value, line 36 does not print anything to the client. If true, errorMessage value is written to client errorMessage session variable used for error messages Else, WelcomeBack value is written to the client welcomeBack session variable displays “welcome back” message to returning users Requests process.asp when form is posted

43 Instantpage.asp Server-side include 68 69 <tr>
<td>Enter the content:</td> 71 <td><textarea name = "content" rows = "3" cols = "50"> 74 Replace this text with the 75 information you would like to post.</textarea></td> </tr> </table> 78 <input type = "submit" value = "submit" /> <input type = "reset" value = "clear" /> </form> 82 <!-- #include virtual = "/includes/footer.shtml" --> </body> 85 </html> Instantpage.asp Server-side include

44 Program Output

45 Program Output

46 Header.shtml server-side include file for the document header
1 <!-- Fig : 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" /> Header.shtml server-side include file for the document header

47 Footer.shtml server-side include file for the document footer
1 <!-- Fig : footer.shtml > 2 <!-- Server-side include file containing XHTML --> 3 <hr style = "color: blue" /> 4 <a style = "text-align: center" href = "mailto:orders">ordering information</a> - 6 <a style = "text-align: center" href = "mailto:editor">contact the editor</a><br /> 8 <hr style = "color: blue" /> Footer.shtml server-side include file for the document footer

48 If statement validates contents of text field.
1 = VBScript %> 2 3 <% ' Fig : process.asp ' ASP document that creates user's ASP document Option Explicit 7 %> 8 9 <% Dim message, q 11 q = Chr( 34 ) ' assign quote character to q Session( "errorMessage" ) = "no error" 14 ' check to make sure that they have entered a ' valid filename If ( LCase( Request( "filename" ) ) = "yourfilename" ) _ Or Request( "filename" ) = "" Then message = "<p style = " & q & "color: red" & q & _ ">" & "Please enter a valid name or filename.</p>" Session( "errorMessage" ) = message Call Server.Transfer( "instantpage.asp" ) End If 24 Dim directoryPath, filePath, fileObject, fileName 26 ' Create a FileSystem Object Set fileObject = Server.CreateObject( _ "Scripting.FileSystemObject" ) 30 directoryPath = _ Request.ServerVariables( "APPL_PHYSICAL_PATH" ) 33 fileName = Request( "filename" ) & ".asp" 35 Process.asp Creates the user’s ASP document and presents a link to the user’s page Requested by instantpage.asp If field is empty or contains default string yourfilename, lines assign XHTML error message to variable message. If statement validates contents of text field. Assign message value to session variable errorMessage FSO object is created if valid user name is entered and assigned reference fileObject Request.ServerVariables retrieves physical path Server method Transfer requests instantpage.asp Specify server path where ASP file is written Builds fileName by concatenating “filename” to the .asp file extension

49 filePath passed FileExists method. Determines if file exists.
' build path for text file filePath = directoryPath & "\" & fileName 38 ' check if the file already exists If fileObject.FileExists( filePath ) Then message = "<p style = " & q & "color: red" & q & _ ">" & "The file name is in use.<br />" & _ "Please use a different file name.</p>" Session( "errorMessage" ) = message Call Server.Transfer( "instantpage.asp" ) End If 47 ' 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 54 Dim header, footer, textFile, openMark, closeMark openMark = "<" & "%" closeMark = "%" & ">" 58 ' build the header. ' vbCrLf inserts a carriage return/linefeed into the text ' string which makes the XHTML code more readable header = openMark & = VBScript " & closeMark _ & vbCrLf & openMark & " ' " & fileName _ & " " & closeMark & vbCrLf & vbCrLf _ & "<!DOC" & "TYPE html PUBLIC " & q & _ "-//W3C//DTD XHTML 1.0 Transitional//EN" & q & _ vbCrLf & q & " & _ "DTD/xhtml1-transitional.dtd" & q & ">" & vbCrLf & _ "<html xmlns = " & q & " & _ q & ">" & vbCrLf & "<head>" & vbCrLf _ Builds file path by concatenating file name to directory path. Assigned to variable filePath. Process.asp Creates the user’s ASP document and presents a link to the user’s page Requested by instantpage.asp filePath passed FileExists method. Determines if file exists. If file exists, variable errorMessage value is set to XHTML containing error message Server Transfer method requests instantpage.asp Assigns XHTML for “welcome back” message to welcomeBack session variable Construct XHTML for header Assign ASP scripting delimeters to string variables openMark and closeMark

50 Form values retrieved using Request object
& "<meta name = " & q & "author" & q & " content = " _ & q & Request( "username" ) & q & " />" & vbCrLf _ & "<meta name = " & q & "pubdate" & q & " content = " _ & q & Date() & q & " />" & vbCrLf _ & "<title>" & Request( "doctitle" ) & "</title>" _ & vbCrLf & "</head>" & vbCrLf & "<body>" & vbCrLf _ & "<!-- #" & "include " & "virtual = " & _ "/includes/header.shtml -->" _ & vbCrLf & "<h2 style = " & q & "text-align: center" & _ q & "><em>" & Request( "doctitle" ) & "</em></h2>" & _ vbCrLf & "<br />" & vbCrLf 82 ' 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>" 93 ' create the ASP file Set textFile = fileObject.CreateTextFile( filePath, False ) With textFile Call .WriteLine( header & Request( "content" ) & _ footer ) Call .Close() End With 101 %> 102 103 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 104 " 105 Form values retrieved using Request object Process.asp Creates the user’s ASP document and presents a link to the user’s page Requested by instantpage.asp footer variable assigned to XHTML footer contents Write header, text area content’s text and footer to text file Lines send XHTML to client that contains link to created page

51 Lines 103-129 send XHTML to client that contains link to created page
106 <html xmlns = " 107 <head> <!-- use the title given by the user --> <title>File Generated: <% =fileName %></title> 111 <style type = "text/css"> h2 { font-family: arial, sans-serif; text-align: center } </style> 116 </head> 118 <body> <!-- #include virtual = "/includes/header.shtml" --> <h2><em>File <% =fileName %> was created successfully.</em> </h2><br /> 124 <!-- provide a link to the generated page --> <a href = "<% =fileName %>">View your file</a> <!-- #include virtual = "/includes/footer.shtml" --> </body> 129 </html> Process.asp Creates the user’s ASP document and presents a link to the user’s page Requested by instantpage.asp Lines send XHTML to client that contains link to created page

52 Test.asp XHTML file created by process.asp
1 = VBScript %> 2 <% ' test.asp %> 3 4 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 5 " 6 <html xmlns = " 7 <head> 8 <meta name = "author" content = "tem" /> 9 <meta name = "pubdate" content = "2/27/2001" /> 10 <title>XML How to Program</title> 11 </head> 12 <body> 13 <!-- Fig : 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>XML How to Program</em></h2> 19 <br /> 20 21 The authoritative Deitel™ Live-Code™ 22 introduction to XML-based systems development. 23 ISBN 24 25 <br /><br /><br /> 26 You have requested this page on 2/27/2001, 27 at 10:14:44 PM. 28 <!-- Fig : footer.shtml > 29 <!-- Server-side include file containing XHTML --> 30 <hr style = "color: blue" /> 31 <a style = "text-align: center" href = "mailto:orders">ordering information</a> - Test.asp XHTML file created by process.asp

53 Test.asp XHTML file created by process.asp Program Output
33 <a style = "text-align: center" href = "mailto:editor">contact the editor</a><br /> 35 <hr style = "color: blue" /> 36 37 </body> 38 </html> Test.asp XHTML file created by process.asp Program Output Fig Welcome back message displayed by instantpage.asp.

54 25.7 Session Tracking and Cookies
Fig Error message generated by instantpage.asp.

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

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

57 Ignores errors until end of script
1 = VBScript %> 2 3 <% ' Fig : database.asp ' ASP document for interacting with the database Option Explicit 7 Dim connection, loginData 9 ' provide error handling code On Error Resume Next Session( "errorString" ) = "" 13 Set connection = Server.CreateObject( "ADODB.Connection" ) Call connection.Open( "login" ) Call errorHandlerLog() 17 ' create the record set Set loginData = Server.CreateObject( "ADODB.Recordset" ) Call loginData.Open( Session( "query" ), connection ) Set Session( "loginData" ) = loginData 22 Call errorHandlerLog() 24 Sub errorHandlerLog() If Err.Number <> 0 Then Dim errorString 28 errorString = Session( "errorString" ) errorString = errorString & "<p class = " & _ Chr( 34 ) & "error" & Chr ( 34 ) & ">Error (" _ & Err.Number & ") in " & Err.Source & "<br />" & _ Err.Description & "</p><br />" Session( "errorString" ) = errorString End If End Sub 37 %> Ignores errors until end of script Server method CreateObject creates ADODB.Connection Database.asp connects to, and queries an Access database CreateObject ADODB.Connection contains functionality necessary to connect to database errorHandlerLog Declares session variable errorString Method Open opens database specified by ODBC System DSN (login) When Open finishes executing, points to first record or EOF if no records were found loginData reference is set to an ADODB.recordset object Open method is passed string containing SQL query and ADODB.Connection object errorHandlerLog processes errors errorHandlerLog called again Err object Number property contains VBScript error number. Tests if error has occurred. Lines define errorHandlerLog If true, errorSrting variable is assigned XHTML text containing error number and message Sets session variable loginData to variable loginData which references the ADODB.Recordset containing all records matching SQL query Error number and message concatenated to variable errorString

58 Assigns SQL query to session variable query
1 = VBScript %> 2 3 <% ' Fig : login.asp ' ASP document to login to instantpage.asp Option Explicit 7 ' create the SQL query Session( "query" ) = "SELECT loginID FROM Users" Call Server.Execute( "database.asp" ) 11 %> 12 13 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 14 " 15 16 <html xmlns = " 17 <head> <title>Login Page</title> 20 <style type = "text/css"> table { text-align: center; font-size: 12pt; color: blue; font-size: 12pt; font-family: arial, sans-serif } error { color: red } </style> 29 </head> 31 <body> 33 <!-- #include virtual="/includes/header.shtml" --> 35 <% Login.asp Identifies users by prompting them for login name and password. Data is stored in Access database login.mdb submitlogin.asp validates the user’s login Assigns SQL query to session variable query Executes database.asp to retrieve login IDs from the database

59 Tests if session variable errorString value is empty string
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, please try again</p> 42 <% End If 43 ' begin the form %> <p>Please select your name and enter your password to login:</p><br /> 47 <form action = "submitlogin.asp" method = "post"> 49 <!-- format the form using a table --> <table border = "0"> <tr> <td>Name:</td> 54 <td> <select name = "loginID"> <option value = "noSelection"> Select your name</option> 59 60 <% If Request.Cookies( "loginID" ) <> "" Then Call BuildReturning() Else Call BuildNewUser() End If 66 %> </select> </td> </tr> 70 Tests if session variable errorString value is empty string Login.asp Prompts user for login name and password. Information is stored in Access database opened in database.asp Lines test is session variable loginFailure is True If false, line 89 prints error message to user select structure builds drop-down list of loginIDs If true, login failure message prints to user and prompts new login Requests loginID cookie Selects the returning user’s login ID option Build loginID options

60 <tr> <td>Password:</td> <td><input type = "password" name = "password" /></td> </tr> 76 <tr> <td></td> <td align = "left"> <input type = "submit" value = "Log Me In" /> </td> </tr> </table> </form> 85 <!-- #include virtual="/includes/footer.shtml" --> 87 <% Else Call Response.Write( Session( "errorString" ) ) End If 91 %> </body> 93 </html> 94 95 <% ' builds the option items for loginIDs and writes ' selected for the loginID of the returning user Sub BuildReturning() Dim found, loginData 100 Set loginData = Session( "loginData" ) 102 ' pull user names from the record set to populate the ' dropdown list Login.asp Prompts user for login name and password. Information is stored in Access database opened in database.asp

61 found set to false before loop Tests for EOF
found = False 106 While Not loginData.EOF ' create this record's dropdown entry 109 %> <option 110 <% ' if we did not write selected for any option ' before If ( Not found ) Then 113 ' 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. If Request.Cookies( "loginID" ) _ = loginData( "loginID" ) Then Call Response.Write( "selected = " & _ Chr( 34 ) & "selected" & Chr( 34 ) ) found = True End If End If 127 %> value = "<% =loginData( "loginID" ) %>"> <% =loginData( "loginID" ) %></option> 129 <% Call loginData.MoveNext() Wend End Sub 132 ' builds the option items for loginIDs without writing ' selected for any loginID Sub BuildNewUser() Dim loginData 137 Set loginData = Session( "loginData" ) 139 found set to false before loop Tests for EOF while loop (lines ) iterates through loginData’s records Login.asp Prompts user for login name and password. Information is stored in Access database opened in database.asp If statement writes selected for an option If statement tests whether option needs to be selected Increments the record set pointer to next record Determines whether current record’s loginID field is equal to loginID cookie If true, lines write selected and set found to true Once selected is written for an option, found set to true Sets option value to current loginID Writes option display as current loginID

62 Login.asp Program Output
' pull user names from the record set to populate the ' dropdown list While Not loginData.EOF ' create this record's dropdown entry 144 %> <option value = "<% =loginData( "loginID" ) %>"> <% =loginData( "loginID" ) %></option> 146 <% Call loginData.MoveNext() Wend End Sub 149 %> Login.asp Program Output

63 Program Output

64 WHERE specifies a condition on which records are selected
1 = VBScript %> 2 3 <% ' Fig : submitlogin.asp ' ASP document to check user's username and password Option Explicit 6 ' test if a user name and a password were ' entered. If not, transfer back to the login page. If Request( "password" ) = "" Or _ Request( "loginID" ) = "noSelection" Then Session( "loginFailure" ) = True Call Server.Transfer( "login.asp" ) End If 14 Dim connection, loginData 16 ' create the SQL query Session( "query" ) = _ "SELECT * FROM Users WHERE loginID = '" & _ Request( "loginID" ) & "'" 21 Call Server.Execute( "database.asp" ) Set loginData = Session( "loginData" ) 24 If Request( "password" ) = loginData( "password" ) Then 26 ' password is OK, adjust loginFailure Session( "loginFailure" ) = False 29 ' write a cookie to recognize them the next time they ' go to login.asp Response.Cookies( "loginID" ) = Request( "loginID" ) 33 ' give it three days to expire Response.Cookies( "loginID" ).Expires = Date() + 3 Lines 9-13 check whether password field is empty or id loginID field contains default value Submitlogin.asp Takes values passed by login.asp and checks values against Users table in database If match is found, user is redirected to instantpage.asp. If not, user is redirected to login.asp. If so, variable loginFailure set to true, client redirected back to login.asp WHERE specifies a condition on which records are selected Sets session variable loginFailure value to False Checks password against the password in recordset Sets reference loginData to session variable loginData (contains records matching query.) Executes database.asp to query database Sets cookie’s expiration date to current date plus 3 days If true, line writes form’s loginID value as cookie named loginID

65 Submitlogin.asp Program Output
36 ' send them to instantpage.asp Call Server.Transfer( "instantpage.asp" ) Else Session( "loginFailure" ) = True Call Server.Transfer( "login.asp" ) End If 43 %> Otherwise loginFailure set to True and client is redirected to login.asp Calls Server method Transfer to redirect client to instantpage.asp Submitlogin.asp Program Output

66 Program Output

67 25.8 Accessing a Database from an Active Server Page
Fig Cookies folder before and after cookie creation.

68 25.8 Accessing a Database from an Active Server Page
Fig Error messages sent to login.asp by database.asp.

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

70 25.9 Server-Side ActiveX Components

71 Creates AdRotator component instance, assigns it reference rotator
1 = VBScript %> 2 3 <% ' Fig : component.asp ' Demonstrating Server-side ActiveX Components Option Explicit 7 %> 8 9 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 10 " 11 12 <html xmlns = " 13 <head> <title>ActiveX Component Example</title> </head> 17 <body> 19 <strong style = "font-family: arial, sans-serif"> Server-side ActiveX Components </strong> 23 <p> 25 <% Dim rotator, browser, information, counter 27 ' create an AdRotator object Set rotator = Server.CreateObject( "MSWC.AdRotator" ) 30 ' use config.txt to send an advertisement to the client Call Response.Write( _ rotator.GetAdvertisement( "config.txt" ) ) 34 Component.asp Uses AdRotator ActiveX component to rotate one of five flag images. When user clicks flag image, country’s corresponding CIA Fact Book Web page displays. Creates AdRotator component instance, assigns it reference rotator Sends advertisement as HTML to client. Method GetAdvertisement called using reference rotator. Retrieves advertisements from config.txt

72 Obtains information about user’s browser Component.asp
' create a BrowserType object Set browser = Server.CreateObject( "MSWC.BrowserType" ) 37 If browser.VBScript = True Then 39 %> <script language = "VBScript"> Call Msgbox( "Client browser supports VBScript!" ) </script> 43 <% End If 45 If browser.JavaScript = True Then 47 %> <script language = "JavaScript"> alert( "Client browser supports JavaScript!" ); </script> 51 <% End If 53 ' 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 " 60 If browser.Cookies Then information = information & "enabled</p><br />" Else information = information & "disabled</p><br />" End If 66 Call Response.Write( information ) 68 Obtains information about user’s browser Component.asp Check property VBScript value If true, lines written to client Passes server variable key HTTP_USER_AGENT to ServerVariables, obtains string containing user information Lines test JavaScript property BrowserType object’s Browser Version and MinorVer properties can obtain similar client information Tests Cookies property to determine if browser supports cookies

73 Increments number of “hits” by one Component.asp
' create Page Counter Object Set counter = Server.CreateObject( "MSWC.PageCounter" ) Call counter.PageHit() ' page has been "hit" 72 %> </p> 74 <p style = "color: blue; font-size: 12pt"> This page has been visited <% =counter.Hits() %> times!</p> </body> 79 </html> Increments number of “hits” by one Component.asp Returns number of “hits”

74 Program Output

75 Program Output

76 Config.txt Describes the advertisements
1 REDIRECT redirect.asp 2 width 54 3 height 36 4 border 1 5 * 6 /images/us.gif 7 8 United States Information 10 /images/france.gif 11 12 France Information 14 /images/germany.gif 15 16 Germany Information 18 /images/italy.gif 19 20 Italy Information 22 /images/spain.gif 23 24 Spain Information Header contains REDIRECT file URL Image URL, destination URL, alt value, image display ratio Advertisement dimensions Asterisk separates header from advertisements Config.txt Describes the advertisements

77 Redirect.asp Redirects user to country’s CIA page when ad is clicked
1 = VBScript %> 2 3 <% ' Fig : redirect.asp ' Redirection Page for AdRotator Component Option Explicit 7 Call Response.Redirect( Request( "url" ) ) 9 %> Redirect.asp Redirects user to country’s CIA page when ad is clicked


Download ppt "Chapter 25 - Active Server Pages (ASP)"

Similar presentations


Ads by Google