...

Lucidi 10

by user

on
Category: Documents
46

views

Report

Comments

Description

Transcript

Lucidi 10
Tecnologie lato Server:
Active Server Pages (ASP)
Stefano Clemente
[email protected]
© 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)
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
22 Novembre 2005
Stefano Clemente
2
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
• I 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
22 Novembre 2005
Stefano Clemente
3
Funzionamento di ASP
• Le pagine ASP sono elaborate da una componente
ActiveX detta scripting engine
• Lo scripting engine è la dll (Dynamic Link Library)
asp.dll
• I 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
22 Novembre 2005
Stefano Clemente
4
Oggetti ASP
• ASP 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 – è l’oggetto usato per accedere alle
informazioni
• passate con una GET o con una POST
• memorizzate nei cookie
• di tipo binario (es. upload di file)
− Response – invia informazioni al client (XHTML,
testo, ecc.)
− Server – fornisce l’accesso ai metodi e alle
proprietà sul server
22 Novembre 2005
Stefano Clemente
5
Esempio 1
<% @LANGUAGE = VBScript %>
<%
' TecnInt26.ppt - Esempio 1: esempio1.asp
Option Explicit
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Esempio 1</title>
<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>
</head>
22 Novembre 2005
Stefano Clemente
6
Esempio 1
<body>
<% Call Response.Write( FormatDateTime( Now, vbLongDate ) ) %>
<p><strong>Esempio 1</strong></p>
<table border = "6">
<tr>
<td>
<% =FormatDateTime( Now, vbLongDate ) %>
</td>
<td>
<% =Time() %>
</td>
</tr>
</table>
</body>
</html>
22 Novembre 2005
<% Call Response.Write( Time () ) %>
Stefano Clemente
7
Esempio 1
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Esempio 1</title>
<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>
</head>
<body>
<p><strong>Esempio 1</strong></p>
<table border = "6">
<tr>
<td>
lunedì 8 dicembre 2003
</td>
<td>
19.48.12
</td>
</tr>
</table>
</body>
</html>
22 Novembre 2005
Stefano Clemente
8
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
− il documento che contiene la form ha l’attributo
action che specifica il documento .asp verso il
quale eseguire la POST
− il documento verso il quale viene eseguita la POST
usa gli oggetti Request per reperire i dati della
form
22 Novembre 2005
Stefano Clemente
9
Esempio 2
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!-- TecnInt16 - Esempio 2 : esempio2.html
-->
<!-- documento XHTML che richiede un documento ASP -->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Name Request</title>
</head>
<body>
<p style = "font-family: arial, sans-serif">
Enter your name:
</p>
<!-- richiede esempio2.asp quando viene eseguita la POST -->
<form action = "esempio2.asp" method = "post">
<input type = "text" name = "namebox" size = "20" />
<input type = "submit" name = "submitButton"
value = "Enter" />
</form>
</body>
</html>
22 Novembre 2005
Stefano Clemente
10
Esempio 2
<% @LANGUAGE = VBScript %>
<%
' TecnInt16 - Esempio 2 : esempio2.asp
' Another simple ASP example
Option Explicit
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Name Information</title>
<style type = "text/css">
p
{ font-family: arial, sans-serif;
font-size: 14pt; color: navy }
.special { font-size: 20pt; color: green }
</style>
</head>
<body>
<!-- retrieve and display namebox's value -->
<p>Hi <% =Request( "namebox" ) %>, </p><br />
<p class = "special">Welcome to ASP!</p>
</body>
</html>
22 Novembre 2005
Stefano Clemente
11
Esempio 2
22 Novembre 2005
Stefano Clemente
12
File System Objects (FSO)
• FSO permettono di manipolare file, directory e drive
• Consentono di leggere e scrivere del testo
• FSO sono oggetti della Microsoft Script Runtime
Library
− 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 – permette di raccogliere informazioni sui file,
manipolarli, aprirli, ecc.
− Folder – permette all’utente di raccogliere informazioni sulle
directory e di manipolarle
− Drive – permette di raccogliere informazioni sui drive
− TextStream – permette di manipolare file di testo
22 Novembre 2005
Stefano Clemente
13
Metodi dell’oggetto
FileSystemObject
Metodo
CopyFile
Descrizione
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 Restituisce una stringa contenente il path
me
assoluto
22 Novembre 2005
Stefano Clemente
14
Metodi dell’oggetto
FileSystemObject
Metodo
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
22 Novembre 2005
Descrizione
Stefano Clemente
15
Proprietà dell’oggetto File
Proprietà
DateCreated
Descrizione
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
22 Novembre 2005
Stefano Clemente
16
Metodi dell’oggetto File
Metodo
Descrizione
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
22 Novembre 2005
Stefano Clemente
17
Proprietà dell’oggetto Folder
Proprietà
Descrizione
Attributes
Intero che indica gli attributi della directory (solalettura, 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
22 Novembre 2005
Stefano Clemente
18
Metodi dell’oggetto Folder
Metodo
Delete
Elimina la directory
Move
Sposta la directory
Copy
Copia la directory
22 Novembre 2005
Descrizione
Stefano Clemente
19
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
22 Novembre 2005
Stefano Clemente
20
Proprietà dell’oggetto TextStream
Proprietà
AtEndOfLine
Descrizione
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 Novembre 2005
Stefano Clemente
21
Metodi dell’oggetto TextStream
Metodo
Descrizione
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
22 Novembre 2005
Stefano Clemente
22
Esempio 3
<% @LANGUAGE = VBScript %>
<% ' Fig. 25.12 : guestbook.asp
' Demonstrating File System Objects
Option Explicit
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>GuestBook Example</title>
<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>
22 Novembre 2005
Stefano Clemente
23
Esempio 3
<%
Dim fileObject, textFile, guestBook, mailtoUrl
' get physical path for this ASP page and
' concatenate guestbook.txt to it
guestbook = Request.ServerVariables( "APPL_PHYSICAL_PATH" ) _
& "\esempio3.txt"
' instantiate a FileSystemObject
Set fileObject = Server.CreateObject( _
"Scripting.FileSystemObject" )
' check if this request is after the user has posted the form
If Request( "hiddenInput" ) = "true" Then
' print a thank you
Call Response.Write( "Thanks for your entry, " & _
Request( "username" ) & "!" )
%>
22 Novembre 2005
Stefano Clemente
24
Esempio 3
<%
' build the mailtoUrl
mailtoUrl = Date() & " <a href = " & Chr( 34 ) _
& "mailto:" & Request( "email" ) & Chr( 34 ) _
& ">" & Request( "username" ) & "</a>: "
' open the guestbook, 8 is for appending
' create the guestbook if it does not exist
Set textFile = _
fileObject.OpenTextFile( guestbook, 8, True )
Crea il file
se non esiste
' write data to guestbook.txt
Append-mode
Call textFile.WriteLine( "<hr />" & mailtoUrl & _
Request( "comment" ) )
<hr />
Call textFile.Close()
End If
%>
22 Novembre 2005
Stefano Clemente
25
Esempio 3
<p>Please leave a message in our guestbook.</p>
<!-- write form to the client -->
<form action = “esempio3.asp" method = "post">
<table>
<tr>
<td>Your Name: </td>
<td><input class = "font"
type = "text" size = "60"
name = "username" /></td>
</tr>
<tr>
<td>Your email address:</td>
<td><input class = "font"
type = "text" size = "60"
name = "email"
value = "[email protected]" />
</td>
</tr>
<tr>
<td>Tell the world: </td>
<td><textarea name = "comment" rows = "3"
cols = "50">
Replace this text with the information you would like to post.</textarea></td>
</tr>
</table>
22 Novembre 2005
Stefano Clemente
26
Esempio 3
<input type = "submit" value = "submit" />
<input type = "reset" value = "clear" />
<input type = "hidden" name = "hiddenInput"
value = "true" />
</form>
<%
' check if the file exists
If fileObject.FileExists( guestBook ) = True Then
' open the guestbook, "1" is for reading
Set textFile = fileObject.OpenTextFile( guestbook, 1 )
' read the entries from the file and write them to
' the client.
Call Response.Write( "Guestbook Entries:<br />" & _
textFile.ReadAll() )
Call textFile.Close()
End If
%>
</body>
</html>
22 Novembre 2005
Stefano Clemente
27
Esempio 3
22 Novembre 2005
Stefano Clemente
28
Esempio 3
22 Novembre 2005
Stefano Clemente
29
22 Novembre 2005
Stefano Clemente
30
Variabili Server
• Le variabili server possono essere lette
passando alcune parole chiave al metodo
ServerVariables di Request
Parola chiave
Descrizione
APPL_PHYSICAL_PA Restituisce il path fisico (rispetto al disco
TH
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
22 Novembre 2005
Stefano Clemente
31
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
• Per la gestione delle sessioni ASP utilizza
l’oggetto Session
− La proprietà Timeout specifica il numero di minuti
in cui una sessione è valida
− Il metodo Abandon termina una sessione
22 Novembre 2005
Stefano Clemente
32
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
• riceve 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
• Imposta 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
22 Novembre 2005
Stefano Clemente
33
Esempio 4
• I documenti ASP dell’esempio contengono anche due
SSI (Server Side Include)
<!-- #include virtual = "/includes/header.shtml" -->
<!-- #include virtual = "/includes/footer.shtml" -->
• Quando lo script engine incontra questi SSI, rimpiazza
queste righe con il contenuto dei file .shtml
specificati
• La parola virtual sta ad indicare che il path è riferito
al path relativo alla root directory del server web
(virtual path)
• È possibile specificare un path relativo alla directory
del file system del server attraverso la parola chiave
file (physical path)
<!-- #include file = "includes\header.shtml" -->
<!-- #include file = "includes\footer.shtml" -->
22 Novembre 2005
Stefano Clemente
34
Esempio 4
<% @LANGUAGE = VBScript %>
<%
' TecnInt 16 - Esempio 4 : esempio4_1.asp
' ASP document that posts data to process.asp
Option Explicit
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Instant Page Content Builder</title>
<style type = "text/css">
table { text-align: center;
font-size: 12pt;
color: blue;
font-size: 12pt;
font-family: arial, sans-serif }
</style>
</head>
22 Novembre 2005
Stefano Clemente
35
Esempio 4
<body>
<!-- include the header
-->
<!-- #include virtual = "/includes/header.shtml" -->
<h2>Instant Page Content Builder</h2>
<% ' 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
%>
22 Novembre 2005
Stefano Clemente
36
Esempio 4
<!-- a form to get the information from the user -->
<form action = "esempio4_2.asp" method = "post">
<table>
<tr>
<td>Your Name: </td>
<td><input type = "text" size = "60"
name = "username" /></td>
</tr>
<tr>
<td>Enter the Filename:</td>
<td><input type = "text" size = "60"
name = "filename"
value = "yourfilename" /></td>
</tr>
<tr>
<td>Enter the Title:</td>
22 Novembre 2005
Stefano Clemente
37
Esempio 4
<td><input type = "text" size = "60"
name = "doctitle"
value = "document title" /></td>
</tr>
<tr>
<td>Enter the content:</td>
<td><textarea name = "content" rows = "3"
cols = "50">
Replace this text with the
information you would like to post.</textarea></td>
</tr>
</table>
<input type = "submit" value = "submit" />
<input type = "reset" value = "clear" />
</form>
<!-- #include virtual = "/includes/footer.shtml" -->
</body>
</html>
22 Novembre 2005
Stefano Clemente
38
Esempio 4
<!-- TecnInt16 - Esempio 4: header.shtml
-->
<!-- Server-side include file containing XHTML -->
<hr style = "color: blue" />
<img height = "100" src = "/images/bug2bug.gif" alt = "Bug" />
<hr style = "color: blue" />
<!-- TecnInt16 - Esempio 4: footer.shtml
-->
<!-- Server-side include file containing XHTML -->
<hr style = "color: blue" />
<a style = "text-align: center"
href = "mailto:orders">ordering information</a> <a style = "text-align: center"
href = "mailto:editor">contact the editor</a><br />
<hr style = "color: blue" />
22 Novembre 2005
Stefano Clemente
39
Esempio 4
<% @LANGUAGE = VBScript %>
<%
' TecnInt 16 - Esempio 4 : esempio4_2.asp
' ASP document that creates user's ASP document
Option Explicit
%>
<%
Dim message, q
q = Chr( 34 ) ' assign quote character to q
Session( "errorMessage" ) = "no error"
' check to make sure that they have entered a
' valid filename
22 Novembre 2005
Stefano Clemente
40
Esempio 4
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( "esempio4_1.asp" )
End If
Dim directoryPath, filePath, fileObject, fileName
' create a FileSystem Object
Set fileObject = Server.CreateObject( _
"Scripting.FileSystemObject" )
directoryPath = _
Request.ServerVariables( "APPL_PHYSICAL_PATH" )
22 Novembre 2005
Stefano Clemente
41
Esempio 4
fileName = Request( "filename" ) & ".asp"
' build path for text file
filePath = directoryPath & "\" & fileName
' 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( "esempio4_1.asp" )
End If
' save XHTML for the welcome back message
22 Novembre 2005
Stefano Clemente
42
Esempio 4
' in a session variable
message = "<p style = " & q & "color: blue" & q & _
">" & "Welcome Back, " & Request( "username" ) & _
"</p><br />"
Session( "welcomeBack" ) = message
Dim header, footer, textFile, openMark, closeMark
openMark = "<" & "%"
closeMark = "%" & ">"
' build the header.
' vbCrLf inserts a carriage return/linefeed into the text
' string which makes the XHTML code more readable
header = openMark & " @LANGUAGE = VBScript " & closeMark _
& vbCrLf & openMark & " ' " & fileName _
& " " & closeMark & vbCrLf & vbCrLf _
22 Novembre 2005
Stefano Clemente
43
Esempio 4
& "<!DOC" & "TYPE html PUBLIC " & q & _
"-//W3C//DTD XHTML 1.0 Transitional//EN" & q & _
vbCrLf & q & "http://www.w3.org/TR/xhtml1/" & _
"DTD/xhtml1-transitional.dtd" & q & ">" & vbCrLf & _
"<html xmlns = " & q & "http://www.w3.org/1999/xhtml" & _
q & ">" & vbCrLf & "<head>" & vbCrLf _
& "<meta name = " & q & "author" & q & " content = " _
& q & Request( "username" ) & q & " />" & vbCrLf _
& "<meta name = " & q & "pubdate" & q & " content = " _
& 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>" & _
22 Novembre 2005
Stefano Clemente
44
Esempio 4
vbCrLf & "<br />" & vbCrLf
' build the footer using a different style for
' building the string
footer = vbCrLf & "<br /><br /><br />" & vbCrLf & _
"You have requested this page on " & _
openMark & " =Date() " & closeMark & "," & _
vbCrLf & "at " & openMark & " =Time() " & _
closeMark & "." & vbCrLf & _
"<!-- #" & "include " & "virtual = " & _
"/includes/footer.shtml -->" _
& vbCrLf & vbCrLf & "</body>" & vbCrLf & "</html>"
' create the ASP file
Set textFile = fileObject.CreateTextFile( filePath, False )
With textFile
22 Novembre 2005
Stefano Clemente
45
Esempio 4
Call .WriteLine( header & Request( "content" ) & _
footer )
Call .Close()
End With
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<!-- use the title given by the user -->
<title>File Generated: <% =fileName %></title>
<style type = "text/css">
22 Novembre 2005
Stefano Clemente
46
Esempio 4
h2 { font-family: arial, sans-serif;
text-align: center }
</style>
</head>
<body>
<!-- #include virtual = "/includes/header.shtml" -->
<h2><em>File <% =fileName %>
was created successfully.</em>
</h2><br />
<!-- provide a link to the generated page -->
<a href = "<% =fileName %>">View your file</a>
<!-- #include virtual = "/includes/footer.shtml" -->
</body>
</html>
22 Novembre 2005
Stefano Clemente
47
22 Novembre 2005
Stefano Clemente
48
22 Novembre 2005
Stefano Clemente
49
22 Novembre 2005
Stefano Clemente
50
22 Novembre 2005
Stefano Clemente
51
22 Novembre 2005
Stefano Clemente
52
22 Novembre 2005
Stefano Clemente
53
22 Novembre 2005
Stefano Clemente
54
Esempio 4
<% @LANGUAGE = VBScript %>
<% ' esempio4_prova.asp %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<meta name = "author" content = "Stefano Clemente" />
<meta name = "pubdate" content = "10/12/2003" />
<title>Esempio 4</title>
</head>
<body>
<!-- #include virtual = /includes/header.shtml -->
<h2 style = "text-align: center"><em>Esempio 4</em></h2>
<br />
<h1>Tecnologie di Internet</h1>
<h3>Lezione di Giovedì 11 Dicembre 2003</h3>
Prova Esempio 4
<br /><br /><br />
You have requested this page on <% =Date() %>,
at <% =Time() %>.
<!-- #include virtual = /includes/footer.shtml -->
</body>
</html>
22 Novembre 2005
Stefano Clemente
55
Cookie
• Ogni interazione tra client e server nel protocollo
HTTP prevede un’intestazione contenente informazioni
sulla natura della richiesta o della risposta
• Quando 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)
22 Novembre 2005
Stefano Clemente
56
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)
• L’oggetto Server dispone del metodo
CreateObject per istanziare altri oggetti
(ActiveX)
22 Novembre 2005
Stefano Clemente
57
Accesso ai database
• Per connettersi a un DB bisogna creare un oggetto
ADODB.Connection, es
Set connessione = Server.CreateObject( "ADODB.Connection" )
• 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 ( "<dsn>" )
• 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 ( "<query>" , connessione )
22 Novembre 2005
Stefano Clemente
58
Esempio 5
• In questo esempio verranno utilizzati cookie e
ADODB per eseguire la login per accedere alla
pagina dell’esempio 4
• Tutti i file necessari per effettuare la login
sono nella directory esempio5 del server
− database.asp
− login.asp
− submitlogin.asp
• Gli utenti con relative password sono
contenuti nel DB Access login.mdb
• Per accedere al DB bisogna creare un DSN
22 Novembre 2005
Stefano Clemente
59
22 Novembre 2005
Stefano Clemente
60
Esempio 5
22 Novembre 2005
Stefano Clemente
61
Esempio 5
22 Novembre 2005
Stefano Clemente
62
Esempio 5
22 Novembre 2005
Stefano Clemente
63
Esempio 5
22 Novembre 2005
Stefano Clemente
64
Esempio 5: database.asp
<% @LANGUAGE = VBScript %>
<%
' Tecnint16 - Esempio 5: database.asp
' ASP document for interacting with the database
Option Explicit
Dim connection, loginData
' provide error handling code
On Error Resume Next
Session( "errorString" ) = ""
Set connection = Server.CreateObject( "ADODB.Connection" )
Call connection.Open( "login" )
Call errorHandlerLog()
' create the record set
22 Novembre 2005
Stefano Clemente
65
Esempio 5: database.asp
Set loginData = Server.CreateObject( "ADODB.Recordset" )
Call loginData.Open( Session( "query" ), connection )
Set Session( "loginData" ) = loginData
Call errorHandlerLog()
Sub errorHandlerLog()
If Err.Number <> 0 Then
Dim errorString
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
%>
22 Novembre 2005
Stefano Clemente
66
Esempio 5: login.asp
<% @LANGUAGE = VBScript %>
<%
' Tecnint16 - Esempio 5: login.asp
' ASP document to login to instantpage.asp
Option Explicit
' create the SQL query
Session( "query" ) = "SELECT loginID FROM Users"
Call Server.Execute( "database.asp" )
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
22 Novembre 2005
Stefano Clemente
67
Esempio 5: login.asp
<title>Login Page</title>
<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>
</head>
<body>
<!-- #include virtual="/includes/header.shtml" -->
<%
If Session( "errorString" ) = "" Then
' if this is a return after a failed attempt,
22 Novembre 2005
Stefano Clemente
68
Esempio 5: login.asp
<%
' print an error
If Session( "loginFailure" ) = True Then %>
<p class = "error">Login attempt failed,
please try again</p>
End If
' begin the form %>
<p>Please select your name and enter
your password to login:</p><br />
<form action = "submitlogin.asp" method = "post">
<!-- format the form using a table -->
<table border = "0">
<tr>
<td>Name:</td>
<td>
22 Novembre 2005
Stefano Clemente
69
Esempio 5: login.asp
<select name = "loginID">
<option value = "noSelection">
Select your name</option>
<%
If Request.Cookies( "loginID" ) <> "" Then
Call BuildReturning()
Else
Call BuildNewUser()
End If
%>
</select>
</td>
</tr>
<tr>
<td>Password:</td>
<td><input type = "password"
name = "password" /></td>
22 Novembre 2005
Stefano Clemente
70
Esempio 5: login.asp
</tr>
<tr>
<td></td>
<td align = "left">
<input type = "submit" value = "Log Me In" />
</td>
</tr>
</table>
</form>
<!-- #include virtual="/includes/footer.shtml" -->
<%
Else
Call Response.Write( Session( "errorString" ) )
End If
%>
</body>
22 Novembre 2005
Stefano Clemente
71
Esempio 5: login.asp
</html>
<%
' builds the option items for loginIDs and writes
' selected for the loginID of the returning user
Sub BuildReturning()
Dim found, loginData
Set loginData = Session( "loginData" )
' pull user names from the record set to populate the
' dropdown list
found = False
%>
<%
While Not loginData.EOF
' create this record's dropdown entry
<option
' if we did not write selected for any option
' before
22 Novembre 2005
Stefano Clemente
72
Esempio 5: login.asp
If ( Not found ) Then
%>
<%
' 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
value = "<% =loginData( "loginID" ) %>">
<% =loginData( "loginID" ) %></option>
Call loginData.MoveNext()
Wend
22 Novembre 2005
Stefano Clemente
73
Esempio 5: login.asp
End Sub
' builds the option items for loginIDs without writing
' selected for any loginID
Sub BuildNewUser()
Dim loginData
Set loginData = Session( "loginData" )
' pull user names from the record set to populate the
' dropdown list
While Not loginData.EOF
' Create this record's dropdown entry
%>
<option value = "<% =loginData( "loginID" ) %>">
<% =loginData( "loginID" ) %></option>
<%
Call loginData.MoveNext()
Wend
End Sub
%>
22 Novembre 2005
Stefano Clemente
74
Esempio 5: submitlogin.asp
<% @LANGUAGE = VBScript %>
<% ' Tecnint16 - Esempio 5: submitlogin.asp
' ASP document to check user's username and password
Option Explicit
' 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
Dim connection, loginData
' create the SQL query
Session( "query" ) = _
"SELECT * FROM Users WHERE loginID = '" & _
Request( "loginID" ) & "'"
22 Novembre 2005
Stefano Clemente
75
Esempio 5: submitlogin.asp
Call Server.Execute( "database.asp" )
Set loginData = Session( "loginData" )
If Request( "password" ) = loginData( "password" ) Then
' password is OK, adjust loginFailure
Session( "loginFailure" ) = False
' write a cookie to recognize them the next time they
' go to login.asp
Response.Cookies( "loginID" ) = Request( "loginID" )
' give it three days to expire
Response.Cookies( "loginID" ).Expires = Date() + 3
' send them to esempio4_1.asp
Call Server.Transfer( "/esempio4_1.asp" )
Else
Session( "loginFailure" ) = True
Call Server.Transfer( "login.asp" )
End If
%>
22 Novembre 2005
Stefano Clemente
76
22 Novembre 2005
Stefano Clemente
77
22 Novembre 2005
Stefano Clemente
78
22 Novembre 2005
Stefano Clemente
79
22 Novembre 2005
Stefano Clemente
80
Fly UP