La presentazione è in caricamento. Aspetta per favore

La presentazione è in caricamento. Aspetta per favore

Tecnologie lato Server: Active Server Pages (ASP) © 2005 Stefano Clemente I lucidi sono in parte realizzati con materiale tratto dal libro di testo adottato.

Presentazioni simili


Presentazione sul tema: "Tecnologie lato Server: Active Server Pages (ASP) © 2005 Stefano Clemente I lucidi sono in parte realizzati con materiale tratto dal libro di testo adottato."— Transcript della presentazione:

1 Tecnologie lato Server: Active Server Pages (ASP) © 2005 Stefano Clemente I lucidi sono in parte realizzati con materiale tratto dal libro di testo adottato tradotto in italiano: © 2002 Prentice Hall H. M. Deitel, P. J. Deitel, T. R. Nieto Internet & World Wide Web – How To Program (Second Edition) Stefano Clemente s.clemente@ei.unibo.it

2 22 Novembre 2005Stefano Clemente2 Riferimenti bibliografici H. M. Deitel, P. J. Deitel, T. R. Nieto Internet & World Wide Web – How To Program (Second Edition) ed. Prentice Hall 2002 Capitolo 24, 25, 26

3 22 Novembre 2005Stefano Clemente3 Introduzione Active Server Pages (ASP) è una tecnologia Microsoft per la creazione di pagine web a contenuto dinamico Attraverso ASP è possibile inviare al client XHTML, controlli ActiveX, Script, Applet asp.dllI documenti ASP sono elaborati da un “motore” per lo scripting chiamato asp.dll ASP permette l’utilizzo di script − dal lato client − dal lato server per la creazione dei contenuti dinamici Il linguaggio di scripting più usato con ASP è VBScript, ma è possibile utilizzare anche JavaScript

4 22 Novembre 2005Stefano Clemente4 Funzionamento di ASP scripting engineLe pagine ASP sono elaborate da una componente ActiveX detta scripting engine asp.dllLo scripting engine è la dll (Dynamic Link Library) asp.dll.aspI file ASP hanno estensione.asp e contengono − tag XHTML − script Quando un client fa richiesta di una pagina ASP, il server, attraverso lo scripting engine − carica in memoria la pagina − la analizza dall’alto verso il basso − interpreta le parti di script mano mano che le incontra − invia il risultato al client

5 22 Novembre 2005Stefano Clemente5 Oggetti ASP oggettiASP dispone di diversi oggetti per offrire ai programmatori metodi diretti per comunicare con i browser raccogliendo i dati dalle richieste HTTP e distinguendo gli utenti − Request − Request – è l’oggetto usato per accedere alle informazioni GETPOSTpassate con una GET o con una POST memorizzate nei cookie di tipo binario (es. upload di file) − Response − Response – invia informazioni al client (XHTML, testo, ecc.) − Server − Server – fornisce l’accesso ai metodi e alle proprietà sul server

6 22 Novembre 2005Stefano Clemente6 Esempio 1 <% ' TecnInt26.ppt - Esempio 1: esempio1.asp ' TecnInt26.ppt - Esempio 1: esempio1.asp Option Explicit Option Explicit%> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> Esempio 1 Esempio 1 td { background-color: black; td { background-color: black; color: yellow } color: yellow } strong { font-family: arial, sans-serif; strong { font-family: arial, sans-serif; font-size: 14pt; color: blue } font-size: 14pt; color: blue } p { font-size: 14pt } p { font-size: 14pt }

7 22 Novembre 2005Stefano Clemente7 Esempio 1 <body> Esempio 1 Esempio 1 </html>

8 22 Novembre 2005Stefano Clemente8 Esempio 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> Esempio 1 Esempio 1 td { background-color: black; td { background-color: black; color: yellow } color: yellow } strong { font-family: arial, sans-serif; strong { font-family: arial, sans-serif; font-size: 14pt; color: blue } font-size: 14pt; color: blue } p { font-size: 14pt } p { font-size: 14pt } Esempio 1 Esempio 1 lunedì 8 dicembre 2003 lunedì 8 dicembre 2003 19.48.12 19.48.12 </html>

9 22 Novembre 2005Stefano Clemente9 Form ASP è utilizzato per elaborare i dati immessi da un utente in una form I dati possono essere immessi dall’utente, inviati al server, elaborati e restituiti al client con un formato diverso Un possibile scenario è quello in cui.asp POST − il documento che contiene la form ha l’attributo action che specifica il documento.asp verso il quale eseguire la POST POST Request − il documento verso il quale viene eseguita la POST usa gli oggetti Request per reperire i dati della form

10 22 Novembre 2005Stefano Clemente10 Esempio 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> Name Request Name Request Enter your name: Enter your name: <input type = "submit" name = "submitButton" <input type = "submit" name = "submitButton" value = "Enter" /> value = "Enter" /> </html>

11 22 Novembre 2005Stefano Clemente11 Esempio 2 <% ' TecnInt16 - Esempio 2 : esempio2.asp ' TecnInt16 - Esempio 2 : esempio2.asp ' Another simple ASP example ' Another simple ASP example Option Explicit Option Explicit%> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> Name Information Name Information p { font-family: arial, sans-serif; p { font-family: arial, sans-serif; font-size: 14pt; color: navy } font-size: 14pt; color: navy }.special { font-size: 20pt; color: green }.special { font-size: 20pt; color: green } Hi, Hi, Welcome to ASP! Welcome to ASP! </html>

12 22 Novembre 2005Stefano Clemente12 Esempio 2

13 22 Novembre 2005Stefano Clemente13 File System Objects (FSO) FSO permettono di manipolare file, directory e drive Consentono di leggere e scrivere del testo Microsoft Script Runtime LibraryFSO sono oggetti della Microsoft Script Runtime Library − FileSystemObject FileFolderDrive − FileSystemObject – permette all’utente di interagire con File, Folder e Drive fornisce metodi per creare directory, spostare file, determinare se un Drive esiste, ecc. − File − File – permette di raccogliere informazioni sui file, manipolarli, aprirli, ecc. − Folder − Folder – permette all’utente di raccogliere informazioni sulle directory e di manipolarle − Drive − Drive – permette di raccogliere informazioni sui drive − TextStream − TextStream – permette di manipolare file di testo

14 22 Novembre 2005Stefano Clemente14 Metodi dell’oggetto FileSystemObject MetodoDescrizione CopyFile Copia un file CopyFolder Copia una directory CreateFolder Crea e restituisce una directory CreateTextFile Crea e restituisce un file di testo DeleteFile Elimina un file DeleteFolder Elimina una directory DriveExists Restituisce un valore booleano che indica se un drive esiste FileExists Restituisce un valore booleano che indica se un file esiste FolderExists Restituisce un valore booleano che indica se una directory esiste GetAbsolutePathNa me Restituisce una stringa contenente il path assoluto

15 22 Novembre 2005Stefano Clemente15 Metodi dell’oggetto FileSystemObject MetodoDescrizione GetDrive Restituisce il drive specificato GetDriveName Restituisce il nome del drive GetFile Restituisce il file specificato GetFileName Restituisce il nome del file GetFolder Restituisce la directory specificata GetParentFolder Name Restituisce il nome della directory genitore GetTempName Crea e restituisce una stringa contenente un nome di file MoveFile Sposta un file MoveFolder Sposta una directory OpenTextFile Apre un file esistente e restituisce un TextStream

16 22 Novembre 2005Stefano Clemente16 Proprietà dell’oggetto File ProprietàDescrizione DateCreated Data di creazione del file DateLastAcces sed Data dell’ultimo accesso al file DateLastModif ied Data dell’ultima modifica al file Drive Drive in cui il file è situato Name Stringa contenente il nome del file ParentFolder Stringa contenente il nome della directory genitore Path Stringa contenente il path del file ShortName Stringa contenente il nome corto del file Size Variant con i byte del file

17 22 Novembre 2005Stefano Clemente17 Metodi dell’oggetto File MetodoDescrizione Copy Copia il file Delete Elimina il file Move Sposta il file OpenAsTextStrea m Apre un file esistente come file di testo e restituisce TextStream

18 22 Novembre 2005Stefano Clemente18 Proprietà dell’oggetto Folder ProprietàDescrizione Attributes Intero che indica gli attributi della directory (sola- lettura, nascosta, ecc.) DateCreated Data di creazione della directory DateLastAccessed Data dell’ultimo accesso alla directory DateLastModified Data dell’ultima modifica della directory Drive Il drive in cui si trova la directory IsRootFolder Booleano che indica se la directory è la radice Name Stringa contenente il nome della directory ParentFolder Directory genitore Path Stringa contenente il path della directory ShortName Stringa contenente il nome corto della directory ShortPath Stringa contenente il path corto della directory Size Variant con i byte di tutte le sottodirectory e file Type Stringa contenente il tipo della cartella

19 22 Novembre 2005Stefano Clemente19 Metodi dell’oggetto Folder MetodoDescrizione Delete Elimina la directory Move Sposta la directory Copy Copia la directory

20 22 Novembre 2005Stefano Clemente20 Proprietà dell’oggetto Drive ProprietàDescrizione AvailableSpace Variant contenente lo spazio disponibile nel drive DriveLetter Stringa contenente la lettera assegnata al drive DriveType Intero contenente il tipo del drive – costanti Unknown, Removable, Fixed, Remote, CDRom e RamDisk FileSystem Stringa contenente la descrizione del file system del drive (FAT, FAT32, NTFS, ecc) FreeSpace Variant contenente lo spazio disponibile nel drive IsReady Booleano che indica se il drive è pronto per l’uso Path Stringa contenente il path del drive RootFolder La directory root del drive SerialNumber Long contenente il serial number del drive TotalSize Variant contenente la capacità del drive VolumeName Stringa contenente il nome del volume del drive

21 22 Novembre 2005Stefano Clemente21 Proprietà dell’oggetto TextStream ProprietàDescrizione AtEndOfLine Booleano che indica se è stata raggiunta la fine di una riga AtEndOfStream Booleano che indica se è stata raggiunta la fine del file Column Colonna relativa al punto di immissione/lettura Line Riga relativa al punto di immissione/lettura

22 22 Novembre 2005Stefano Clemente22 Metodi dell’oggetto TextStream MetodoDescrizione Read Restituisce una stringa contenente il numero di caratteri richiesto ReadAll Stringa contenente l’intero file ReadLine Stringa contenente una riga del file Write Scrive una stringa sul file WriteBlankLines Scrive dei new line WriteLine Scrive una riga nel file Skip Salta il numero specificato (variant) di caratteri SkipLine Salta una riga di caratteri Close Chiude il file

23 22 Novembre 2005Stefano Clemente23 Esempio 3 <% ' Fig. 25.12 : guestbook.asp ' Demonstrating File System Objects ' Demonstrating File System Objects Option Explicit Option Explicit%> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> GuestBook Example GuestBook Example hr { size: 1; color: blue } hr { size: 1; color: blue } table { text-align: center } table { text-align: center } td { font-size: 12pt } td { font-size: 12pt } p { font-size: 14pt; color: blue } p { font-size: 14pt; color: blue }.font { font-family: arial, sans-serif }.font { font-family: arial, sans-serif }

24 22 Novembre 2005Stefano Clemente24 Esempio 3 <% Dim fileObject, textFile, guestBook, mailtoUrl Dim fileObject, textFile, guestBook, mailtoUrl ' get physical path for this ASP page and ' get physical path for this ASP page and ' concatenate guestbook.txt to it ' concatenate guestbook.txt to it guestbook = Request.ServerVariables( "APPL_PHYSICAL_PATH" ) _ guestbook = Request.ServerVariables( "APPL_PHYSICAL_PATH" ) _ & "\esempio3.txt" & "\esempio3.txt" ' instantiate a FileSystemObject ' instantiate a FileSystemObject Set fileObject = Server.CreateObject( _ Set fileObject = Server.CreateObject( _ "Scripting.FileSystemObject" ) "Scripting.FileSystemObject" ) ' check if this request is after the user has posted the form ' check if this request is after the user has posted the form If Request( "hiddenInput" ) = "true" Then If Request( "hiddenInput" ) = "true" Then ' print a thank you ' print a thank you Call Response.Write( "Thanks for your entry, " & _ Call Response.Write( "Thanks for your entry, " & _ Request( "username" ) & "!" ) Request( "username" ) & "!" )%>

25 22 Novembre 2005Stefano Clemente25 Esempio 3 <% ' build the mailtoUrl ' build the mailtoUrl mailtoUrl = Date() & " <a href = " & Chr( 34 ) _ mailtoUrl = Date() & " <a href = " & Chr( 34 ) _ & "mailto:" & Request( "email" ) & Chr( 34 ) _ & "mailto:" & Request( "email" ) & Chr( 34 ) _ & ">" & Request( "username" ) & " : " & ">" & Request( "username" ) & " : " ' open the guestbook, 8 is for appending ' open the guestbook, 8 is for appending ' create the guestbook if it does not exist ' create the guestbook if it does not exist Set textFile = _ Set textFile = _ fileObject.OpenTextFile( guestbook, 8, True ) fileObject.OpenTextFile( guestbook, 8, True ) ' write data to guestbook.txt ' write data to guestbook.txt Call textFile.WriteLine( " " & mailtoUrl & _ Call textFile.WriteLine( " " & mailtoUrl & _ Request( "comment" ) ) Request( "comment" ) ) Call textFile.Close() Call textFile.Close() End If End If%> Append-mode Crea il file se non esiste

26 22 Novembre 2005Stefano Clemente26 Esempio 3 Please leave a message in our guestbook. Please leave a message in our guestbook. Your Name: Your Name: <input class = "font" type = "text" size = "60" type = "text" size = "60" name = "username" /> name = "username" /> Your email address: Your email address: <input class = "font" type = "text" size = "60" type = "text" size = "60" name = "email" name = "email" value = "user@isp.com" /> value = "user@isp.com" /> Tell the world: Tell the world: <textarea name = "comment" rows = "3" cols = "50"> cols = "50"> Replace this text with the information you would like to post. Replace this text with the information you would like to post.

27 22 Novembre 2005Stefano Clemente27 Esempio 3 <input type = "hidden" name = "hiddenInput" <input type = "hidden" name = "hiddenInput" value = "true" /> value = "true" /> <% ' check if the file exists ' check if the file exists If fileObject.FileExists( guestBook ) = True Then If fileObject.FileExists( guestBook ) = True Then ' open the guestbook, "1" is for reading ' open the guestbook, "1" is for reading Set textFile = fileObject.OpenTextFile( guestbook, 1 ) Set textFile = fileObject.OpenTextFile( guestbook, 1 ) ' read the entries from the file and write them to ' read the entries from the file and write them to ' the client. ' the client. Call Response.Write( "Guestbook Entries: " & _ Call Response.Write( "Guestbook Entries: " & _ textFile.ReadAll() ) textFile.ReadAll() ) Call textFile.Close() Call textFile.Close() End If End If%> </html>

28 22 Novembre 2005Stefano Clemente28 Esempio 3

29 22 Novembre 2005Stefano Clemente29 Esempio 3

30 22 Novembre 2005Stefano Clemente30

31 22 Novembre 2005Stefano Clemente31 Variabili Server ServerVariablesRequestLe variabili server possono essere lette passando alcune parole chiave al metodo ServerVariables di Request Parola chiave Descrizione APPL_PHYSICAL_PA TH Restituisce il path fisico (rispetto al disco del server e non rispetto alla document root del web server) HTTPS Booleano che indica se la richiesta arriva da SSL REMOTE_ADDR Nome DNS o indirizzo IP del client REQUEST_METHOD Metodo richiesta (GET, POST) SERVER_NAME Nome DNS o indirizzo IP del server HTTP_USER_AGENT Restituisce informazioni sul browser HTTP_COOKIE Restituisce il cookie residente sul client

32 22 Novembre 2005Stefano Clemente32 Session Tracking Il server realizza il session tracking registrando le visite al sito da parte dell’utenza Alla prima connessione il server assegna al client un identificativo univoco (session ID) Ogni volta che il client esegue una richiesta il server confronta il session ID del client con tutti quelli che ha memorizzato SessionPer la gestione delle sessioni ASP utilizza l’oggetto Session Timeout − La proprietà Timeout specifica il numero di minuti in cui una sessione è valida Abandon − Il metodo Abandon termina una sessione

33 22 Novembre 2005Stefano Clemente33 Esempio 4 Questo esempio mostra un generatore di pagine ASP L’utente può immettere attraverso una form le informazioni che vuole visualizzare nella pagina e il generatore di pagine ASP provvede a creare la relativa pagina Ci sono due pagine − esempio4_1.asp contiene la form per la richiesta delle informazioni all’utente − esempio4_2.asp esempio4_1.asp esempio4_1.asp errorMessagericeve i dati fa esempio4_1.asp e se non ci sono errori crea la nuova pagina, altrimenti richiama esempio4_1.asp passando un messaggio di errore attraverso la variabile di sessione errorMessage welcomeBack esempio4_1.aspImposta un messaggio di bentornato attraverso la variabile di sessione welcomeBack nel caso in cui l’utente caricasse nuovamente esempio4_1.asp all’interno della stessa sessione

34 22 Novembre 2005Stefano Clemente34 Esempio 4 I documenti ASP dell’esempio contengono anche due SSI (Server Side Include).shtmlQuando lo script engine incontra questi SSI, rimpiazza queste righe con il contenuto dei file.shtml specificati virtual virtual pathLa parola virtual sta ad indicare che il path è riferito al path relativo alla root directory del server web (virtual path) file physical pathÈ possibile specificare un path relativo alla directory del file system del server attraverso la parola chiave file (physical path)

35 22 Novembre 2005Stefano Clemente35 Esempio 4 <% ' TecnInt 16 - Esempio 4 : esempio4_1.asp ' TecnInt 16 - Esempio 4 : esempio4_1.asp ' ASP document that posts data to process.asp ' ASP document that posts data to process.asp Option Explicit Option Explicit%> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> Instant Page Content Builder Instant Page Content Builder table { text-align: center; table { text-align: center; font-size: 12pt; font-size: 12pt; color: blue; color: blue; font-size: 12pt; font-size: 12pt; font-family: arial, sans-serif } font-family: arial, sans-serif }

36 22 Novembre 2005Stefano Clemente36 Esempio 4 Instant Page Content Builder Instant Page Content Builder <% ' if process.asp posted an error, print the error ' message. ' message. If Session( "errormessage" ) <> "no error" Then If Session( "errormessage" ) <> "no error" Then Call Response.Write( Session( "errorMessage" ) ) Call Response.Write( Session( "errorMessage" ) ) ' otherwise, print the welcome back message, if any. ' otherwise, print the welcome back message, if any. Else Else Call Response.Write( Session( "welcomeBack" ) ) Call Response.Write( Session( "welcomeBack" ) ) End If End If%>

37 22 Novembre 2005Stefano Clemente37 Esempio 4 Your Name: Your Name: <input type = "text" size = "60" name = "username" /> name = "username" /> Enter the Filename: Enter the Filename: <input type = "text" size = "60" name = "filename" name = "filename" value = "yourfilename" /> value = "yourfilename" /> Enter the Title: Enter the Title:

38 22 Novembre 2005Stefano Clemente38 Esempio 4 <input type = "text" size = "60" name = "doctitle" name = "doctitle" value = "document title" /> value = "document title" /> Enter the content: Enter the content: <textarea name = "content" rows = "3" cols = "50"> cols = "50"> Replace this text with the information you would like to post. information you would like to post. </html>

39 22 Novembre 2005Stefano Clemente39 Esempio 4 <a style = "text-align: center" href = "mailto:orders">ordering information - href = "mailto:orders">ordering information - <a style = "text-align: center" href = "mailto:editor">contact the editor href = "mailto:editor">contact the editor

40 22 Novembre 2005Stefano Clemente40 Esempio 4 <% ' TecnInt 16 - Esempio 4 : esempio4_2.asp ' TecnInt 16 - Esempio 4 : esempio4_2.asp ' ASP document that creates user's ASP document ' ASP document that creates user's ASP document Option Explicit Option Explicit%><% Dim message, q Dim message, q q = Chr( 34 ) ' assign quote character to q q = Chr( 34 ) ' assign quote character to q Session( "errorMessage" ) = "no error" Session( "errorMessage" ) = "no error" ' check to make sure that they have entered a ' check to make sure that they have entered a ' valid filename ' valid filename

41 22 Novembre 2005Stefano Clemente41 Esempio 4 If ( LCase( Request( "filename" ) ) = "yourfilename" ) _ If ( LCase( Request( "filename" ) ) = "yourfilename" ) _ Or Request( "filename" ) = "" Then Or Request( "filename" ) = "" Then message = "<p style = " & q & "color: red" & q & _ message = "<p style = " & q & "color: red" & q & _ ">" & "Please enter a valid name or filename. " ">" & "Please enter a valid name or filename. " Session( "errorMessage" ) = message Session( "errorMessage" ) = message Call Server.Transfer( "esempio4_1.asp" ) Call Server.Transfer( "esempio4_1.asp" ) End If End If Dim directoryPath, filePath, fileObject, fileName Dim directoryPath, filePath, fileObject, fileName ' create a FileSystem Object ' create a FileSystem Object Set fileObject = Server.CreateObject( _ Set fileObject = Server.CreateObject( _ "Scripting.FileSystemObject" ) "Scripting.FileSystemObject" ) directoryPath = _ directoryPath = _ Request.ServerVariables( "APPL_PHYSICAL_PATH" ) Request.ServerVariables( "APPL_PHYSICAL_PATH" )

42 22 Novembre 2005Stefano Clemente42 Esempio 4 fileName = Request( "filename" ) & ".asp" fileName = Request( "filename" ) & ".asp" ' build path for text file ' build path for text file filePath = directoryPath & "\" & fileName filePath = directoryPath & "\" & fileName ' check if the file already exists ' check if the file already exists If fileObject.FileExists( filePath ) Then If fileObject.FileExists( filePath ) Then message = "<p style = " & q & "color: red" & q & _ message = "<p style = " & q & "color: red" & q & _ ">" & "The file name is in use. " & _ ">" & "The file name is in use. " & _ "Please use a different file name. " "Please use a different file name. " Session( "errorMessage" ) = message Session( "errorMessage" ) = message Call Server.Transfer( "esempio4_1.asp" ) Call Server.Transfer( "esempio4_1.asp" ) End If End If ' save XHTML for the welcome back message ' save XHTML for the welcome back message

43 22 Novembre 2005Stefano Clemente43 Esempio 4 ' in a session variable ' in a session variable message = "<p style = " & q & "color: blue" & q & _ message = "<p style = " & q & "color: blue" & q & _ ">" & "Welcome Back, " & Request( "username" ) & _ ">" & "Welcome Back, " & Request( "username" ) & _ " " " " Session( "welcomeBack" ) = message Session( "welcomeBack" ) = message Dim header, footer, textFile, openMark, closeMark Dim header, footer, textFile, openMark, closeMark openMark = "<" & "%" openMark = "<" & "%" closeMark = "%" & ">" closeMark = "%" & ">" ' build the header. ' build the header. ' vbCrLf inserts a carriage return/linefeed into the text ' vbCrLf inserts a carriage return/linefeed into the text ' string which makes the XHTML code more readable ' string which makes the XHTML code more readable header = openMark & " @LANGUAGE = VBScript " & closeMark _ header = openMark & " @LANGUAGE = VBScript " & closeMark _ & vbCrLf & openMark & " ' " & fileName _ & vbCrLf & openMark & " ' " & fileName _ & " " & closeMark & vbCrLf & vbCrLf _ & " " & closeMark & vbCrLf & vbCrLf _

44 22 Novembre 2005Stefano Clemente44 Esempio 4 & "<!DOC" & "TYPE html PUBLIC " & q & _ & "<!DOC" & "TYPE html PUBLIC " & q & _ "-//W3C//DTD XHTML 1.0 Transitional//EN" & q & _ "-//W3C//DTD XHTML 1.0 Transitional//EN" & q & _ vbCrLf & q & "http://www.w3.org/TR/xhtml1/" & _ vbCrLf & q & "http://www.w3.org/TR/xhtml1/" & _ "DTD/xhtml1-transitional.dtd" & q & ">" & vbCrLf & _ "DTD/xhtml1-transitional.dtd" & q & ">" & vbCrLf & _ "<html xmlns = " & q & "http://www.w3.org/1999/xhtml" & _ "<html xmlns = " & q & "http://www.w3.org/1999/xhtml" & _ q & ">" & vbCrLf & " " & vbCrLf _ q & ">" & vbCrLf & " " & vbCrLf _ & "<meta name = " & q & "author" & q & " content = " _ & "<meta name = " & q & "author" & q & " content = " _ & q & Request( "username" ) & q & " />" & vbCrLf _ & q & Request( "username" ) & q & " />" & vbCrLf _ & "<meta name = " & q & "pubdate" & q & " content = " _ & "<meta name = " & q & "pubdate" & q & " content = " _ & q & Date() & q & " />" & vbCrLf _ & q & Date() & q & " />" & vbCrLf _ & " " & Request( "doctitle" ) & " " _ & " " & Request( "doctitle" ) & " " _ & vbCrLf & " " & vbCrLf & " " & vbCrLf _ & vbCrLf & " " & vbCrLf & " " & vbCrLf _ & "<!-- #" & "include " & "virtual = " & _ & "<!-- #" & "include " & "virtual = " & _ "/includes/header.shtml -->" _ "/includes/header.shtml -->" _ & vbCrLf & "<h2 style = " & q & "text-align: center" & _ & vbCrLf & "<h2 style = " & q & "text-align: center" & _ q & "> " & Request( "doctitle" ) & " " & _ q & "> " & Request( "doctitle" ) & " " & _

45 22 Novembre 2005Stefano Clemente45 Esempio 4 vbCrLf & " " & vbCrLf vbCrLf & " " & vbCrLf ' build the footer using a different style for ' build the footer using a different style for ' building the string ' building the string footer = vbCrLf & " " & vbCrLf & _ footer = vbCrLf & " " & vbCrLf & _ "You have requested this page on " & _ "You have requested this page on " & _ openMark & " =Date() " & closeMark & "," & _ openMark & " =Date() " & closeMark & "," & _ vbCrLf & "at " & openMark & " =Time() " & _ vbCrLf & "at " & openMark & " =Time() " & _ closeMark & "." & vbCrLf & _ closeMark & "." & vbCrLf & _ "<!-- #" & "include " & "virtual = " & _ "<!-- #" & "include " & "virtual = " & _ "/includes/footer.shtml -->" _ "/includes/footer.shtml -->" _ & vbCrLf & vbCrLf & " " & vbCrLf & " " & vbCrLf & vbCrLf & " " & vbCrLf & " " ' create the ASP file ' create the ASP file Set textFile = fileObject.CreateTextFile( filePath, False ) Set textFile = fileObject.CreateTextFile( filePath, False ) With textFile With textFile

46 22 Novembre 2005Stefano Clemente46 Esempio 4 Call.WriteLine( header & Request( "content" ) & _ Call.WriteLine( header & Request( "content" ) & _ footer ) footer ) Call.Close() Call.Close() End With End With%> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> File Generated: File Generated:

47 22 Novembre 2005Stefano Clemente47 Esempio 4 h2 { font-family: arial, sans-serif; h2 { font-family: arial, sans-serif; text-align: center } text-align: center } File File was created successfully. was created successfully. ">View your file ">View your file </html>

48 22 Novembre 2005Stefano Clemente48

49 22 Novembre 2005Stefano Clemente49

50 22 Novembre 2005Stefano Clemente50

51 22 Novembre 2005Stefano Clemente51

52 22 Novembre 2005Stefano Clemente52

53 22 Novembre 2005Stefano Clemente53

54 22 Novembre 2005Stefano Clemente54

55 22 Novembre 2005Stefano Clemente55 Esempio 4 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <head> Esempio 4 Esempio 4 </head><body> Esempio 4 Esempio 4 Tecnologie di Internet Tecnologie di Internet Lezione di Giovedì 11 Dicembre 2003 Lezione di Giovedì 11 Dicembre 2003 Prova Esempio 4 You have requested this page on, at. </body></html>

56 22 Novembre 2005Stefano Clemente56 Cookie Ogni interazione tra client e server nel protocollo HTTP prevede un’intestazione contenente informazioni sulla natura della richiesta o della risposta getpostQuando un’ASP riceve una richiesta l’intestazione contiene il tipo di richiesta ( get o post ) e i cookie memorizzati sul client dal server Quando il server fornisce una risposta, essa contiene i cookie che il server vuole memorizzare sul client I cookie possono essere − mantenuti sul client per l’intera durata della sessione − memorizzati sul client per usi futuri I cookie sono eliminati in modo automatico quando scadono (expire)

57 22 Novembre 2005Stefano Clemente57 Accesso ai database Gli applicativi Web sono di solito applicativi client-server a tre livelli, in cui il livello centrale (il web server) esegue gli accessi a un database (DB) ASP possono comunicare con i DB per mezzo di ADO (ActiveX Data Object) CreateObjectL’oggetto Server dispone del metodo CreateObject per istanziare altri oggetti (ActiveX)

58 22 Novembre 2005Stefano Clemente58 Accesso ai database ADODB.Connection Set connessione = Server.CreateObject( "ADODB.Connection" )Per connettersi a un DB bisogna creare un oggetto ADODB.Connection, es Set connessione = Server.CreateObject( "ADODB.Connection" ) Open Call connessione.Open ( " " )Una volta creato l’oggetto si richiama su di esso il metodo Open per aprire il DB relativo a uno specifico Data Source Name (DSN) Call connessione.Open ( " " ) ADODB.RecordsetOpen Set dati = Server.CreateObject( "ADODB.Recordset" ) Call dati.Open ( " ", connessione )Per eseguire una query sul DB è possibile istanziare l’oggetto ADODB.Recordset e eseguire il metodo Open di quest’ultimo con la query richiesta come argomento Set dati = Server.CreateObject( "ADODB.Recordset" ) Call dati.Open ( " ", connessione )

59 22 Novembre 2005Stefano Clemente59 Esempio 5 In questo esempio verranno utilizzati cookie e ADODB per eseguire la login per accedere alla pagina dell’esempio 4 esempio5Tutti i file necessari per effettuare la login sono nella directory esempio5 del server − database.asp − login.asp − submitlogin.asp login.mdbGli utenti con relative password sono contenuti nel DB Access login.mdb Per accedere al DB bisogna creare un DSN

60 22 Novembre 2005Stefano Clemente60

61 22 Novembre 2005Stefano Clemente61 Esempio 5

62 22 Novembre 2005Stefano Clemente62 Esempio 5

63 22 Novembre 2005Stefano Clemente63 Esempio 5

64 22 Novembre 2005Stefano Clemente64 Esempio 5

65 22 Novembre 2005Stefano Clemente65 Esempio 5: database.asp <% ' Tecnint16 - Esempio 5: database.asp ' Tecnint16 - Esempio 5: database.asp ' ASP document for interacting with the database ' ASP document for interacting with the database Option Explicit Option Explicit Dim connection, loginData Dim connection, loginData ' provide error handling code ' provide error handling code On Error Resume Next On Error Resume Next Session( "errorString" ) = "" Session( "errorString" ) = "" Set connection = Server.CreateObject( "ADODB.Connection" ) Set connection = Server.CreateObject( "ADODB.Connection" ) Call connection.Open( "login" ) Call connection.Open( "login" ) Call errorHandlerLog() Call errorHandlerLog() ' create the record set ' create the record set

66 22 Novembre 2005Stefano Clemente66 Esempio 5: database.asp Set loginData = Server.CreateObject( "ADODB.Recordset" ) Set loginData = Server.CreateObject( "ADODB.Recordset" ) Call loginData.Open( Session( "query" ), connection ) Call loginData.Open( Session( "query" ), connection ) Set Session( "loginData" ) = loginData Set Session( "loginData" ) = loginData Call errorHandlerLog() Call errorHandlerLog() Sub errorHandlerLog() Sub errorHandlerLog() If Err.Number <> 0 Then If Err.Number <> 0 Then Dim errorString Dim errorString errorString = Session( "errorString" ) errorString = Session( "errorString" ) errorString = errorString & "<p class = " & _ errorString = errorString & "<p class = " & _ Chr( 34 ) & "error" & Chr ( 34 ) & ">Error (" _ Chr( 34 ) & "error" & Chr ( 34 ) & ">Error (" _ & Err.Number & ") in " & Err.Source & " " & _ & Err.Number & ") in " & Err.Source & " " & _ Err.Description & " " Err.Description & " " Session( "errorString" ) = errorString Session( "errorString" ) = errorString End If End If End Sub End Sub%>

67 22 Novembre 2005Stefano Clemente67 Esempio 5: login.asp <% ' Tecnint16 - Esempio 5: login.asp ' Tecnint16 - Esempio 5: login.asp ' ASP document to login to instantpage.asp ' ASP document to login to instantpage.asp Option Explicit Option Explicit ' create the SQL query ' create the SQL query Session( "query" ) = "SELECT loginID FROM Users" Session( "query" ) = "SELECT loginID FROM Users" Call Server.Execute( "database.asp" ) Call Server.Execute( "database.asp" )%> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

68 22 Novembre 2005Stefano Clemente68 Esempio 5: login.asp Login Page Login Page table { text-align: center; table { text-align: center; font-size: 12pt; font-size: 12pt; color: blue; color: blue; font-size: 12pt; font-size: 12pt; font-family: arial, sans-serif } font-family: arial, sans-serif }.error { color: red }.error { color: red } <% If Session( "errorString" ) = "" Then If Session( "errorString" ) = "" Then ' if this is a return after a failed attempt, ' if this is a return after a failed attempt,

69 22 Novembre 2005Stefano Clemente69 Esempio 5: login.asp ' print an error ' print an error If Session( "loginFailure" ) = True Then %> If Session( "loginFailure" ) = True Then %> Login attempt failed, Login attempt failed, please try again please try again <% End If ' begin the form %> ' begin the form %> Please select your name and enter Please select your name and enter your password to login: your password to login: Name: Name:

70 22 Novembre 2005Stefano Clemente70 Esempio 5: login.asp Select your name Select your name <% If Request.Cookies( "loginID" ) <> "" Then If Request.Cookies( "loginID" ) <> "" Then Call BuildReturning() Call BuildReturning() Else Else Call BuildNewUser() Call BuildNewUser() End If End If%> Password: Password: <input type = "password" name = "password" /> name = "password" />

71 22 Novembre 2005Stefano Clemente71 Esempio 5: login.asp <% Else Else Call Response.Write( Session( "errorString" ) ) Call Response.Write( Session( "errorString" ) ) End If End If%>

72 22 Novembre 2005Stefano Clemente72 Esempio 5: login.asp </html><% ' builds the option items for loginIDs and writes ' builds the option items for loginIDs and writes ' selected for the loginID of the returning user ' selected for the loginID of the returning user Sub BuildReturning() Sub BuildReturning() Dim found, loginData Dim found, loginData Set loginData = Session( "loginData" ) Set loginData = Session( "loginData" ) ' pull user names from the record set to populate the ' pull user names from the record set to populate the ' dropdown list ' dropdown list found = False found = False While Not loginData.EOF While Not loginData.EOF ' create this record's dropdown entry ' create this record's dropdown entry %> <option <% ' if we did not write selected for any option ' before ' before

73 22 Novembre 2005Stefano Clemente73 Esempio 5: login.asp If ( Not found ) Then If ( Not found ) Then ' if the current record's loginID is equal to ' if the current record's loginID is equal to ' the loginID cookie, then it is the loginID of ' the loginID cookie, then it is the loginID of ' the returning user, and thus we need to write ' the returning user, and thus we need to write ' selected for this option; in this case we also ' selected for this option; in this case we also ' need to signal that we have written selected ' need to signal that we have written selected ' for an option by setting found to True. ' for an option by setting found to True. If Request.Cookies( "loginID" ) _ If Request.Cookies( "loginID" ) _ = loginData( "loginID" ) Then = loginData( "loginID" ) Then Call Response.Write( "selected = " & _ Call Response.Write( "selected = " & _ Chr( 34 ) & "selected" & Chr( 34 ) ) Chr( 34 ) & "selected" & Chr( 34 ) ) found = True found = True End If End If %> value = " "> <% Call loginData.MoveNext() Wend Wend

74 22 Novembre 2005Stefano Clemente74 Esempio 5: login.asp End Sub End Sub ' builds the option items for loginIDs without writing ' builds the option items for loginIDs without writing ' selected for any loginID ' selected for any loginID Sub BuildNewUser() Sub BuildNewUser() Dim loginData Dim loginData Set loginData = Session( "loginData" ) Set loginData = Session( "loginData" ) ' pull user names from the record set to populate the ' pull user names from the record set to populate the ' dropdown list ' dropdown list While Not loginData.EOF While Not loginData.EOF ' Create this record's dropdown entry ' Create this record's dropdown entry %> "> <% Call loginData.MoveNext() Wend Wend End Sub End Sub%>

75 22 Novembre 2005Stefano Clemente75 Esempio 5: submitlogin.asp <% ' Tecnint16 - Esempio 5: submitlogin.asp ' ASP document to check user's username and password ' ASP document to check user's username and password Option Explicit Option Explicit ' test if a user name and a password were ' test if a user name and a password were ' entered. If not, transfer back to the login page. ' entered. If not, transfer back to the login page. If Request( "password" ) = "" Or _ If Request( "password" ) = "" Or _ Request( "loginID" ) = "noSelection" Then Request( "loginID" ) = "noSelection" Then Session( "loginFailure" ) = True Session( "loginFailure" ) = True Call Server.Transfer( "login.asp" ) Call Server.Transfer( "login.asp" ) End If End If Dim connection, loginData Dim connection, loginData ' create the SQL query ' create the SQL query Session( "query" ) = _ Session( "query" ) = _ "SELECT * FROM Users WHERE loginID = '" & _ "SELECT * FROM Users WHERE loginID = '" & _ Request( "loginID" ) & "'" Request( "loginID" ) & "'"

76 22 Novembre 2005Stefano Clemente76 Esempio 5: submitlogin.asp Call Server.Execute( "database.asp" ) Call Server.Execute( "database.asp" ) Set loginData = Session( "loginData" ) Set loginData = Session( "loginData" ) If Request( "password" ) = loginData( "password" ) Then If Request( "password" ) = loginData( "password" ) Then ' password is OK, adjust loginFailure ' password is OK, adjust loginFailure Session( "loginFailure" ) = False Session( "loginFailure" ) = False ' write a cookie to recognize them the next time they ' write a cookie to recognize them the next time they ' go to login.asp ' go to login.asp Response.Cookies( "loginID" ) = Request( "loginID" ) Response.Cookies( "loginID" ) = Request( "loginID" ) ' give it three days to expire ' give it three days to expire Response.Cookies( "loginID" ).Expires = Date() + 3 Response.Cookies( "loginID" ).Expires = Date() + 3 ' send them to esempio4_1.asp ' send them to esempio4_1.asp Call Server.Transfer( "/esempio4_1.asp" ) Call Server.Transfer( "/esempio4_1.asp" ) Else Else Session( "loginFailure" ) = True Session( "loginFailure" ) = True Call Server.Transfer( "login.asp" ) Call Server.Transfer( "login.asp" ) End If End If%>

77 22 Novembre 2005Stefano Clemente77

78 22 Novembre 2005Stefano Clemente78

79 22 Novembre 2005Stefano Clemente79

80 22 Novembre 2005Stefano Clemente80


Scaricare ppt "Tecnologie lato Server: Active Server Pages (ASP) © 2005 Stefano Clemente I lucidi sono in parte realizzati con materiale tratto dal libro di testo adottato."

Presentazioni simili


Annunci Google