Title: Database Access from Web Servers
1Database Access from Web Servers
2Motivazioni
- Produrre pagine al volo in base alle esigenze
dellutente e da contenuti strutturati (p.e.
database) - Scripting componenti client-side non bastano
- Soluzioni
- Architetture per produrre contenuti dinamici a
lato-server
3Web Server estensioni
- CGI (Common Gateway Interface)
- Web Server launches application named in URL
- CGI application gets HTTP headers URL arguments
- CGI application returns HTTP headers and HTML
document - Runs in separate process from Web Server
- High startup cost (load plus process creation)
- Typically written in C, C, Perl
4Web Server estensioni
- ISAPI (Internet Server API)
- Microsoft Internet Information Server high
performance API - Functionally similar to CGI, but runs much faster
- Runs in same process as Web Server
- Low startup cost (after first load, stays in
memory) - Typically written in C, C
- Netscape NSAPI is similar
5Common Gateway Interface
- Interfaccia che consente al Web Server di
eseguire applicazioni esterne in grado di creare
pagine dinamicamente
6Caratteristiche di CGI
- Non e
- un linguaggio di programmazione
- un protocollo di comunicazione
- Definisce solo un insieme di variabili di
ambiente utili alla applicazione (ad es.
parametri inviati dal client)
7Invocazione
- Il cliente specifica nellURL il nome del
programma da eseguire - Il programma deve stare in una posizione precisa
(di solito il direttorio cgi-bin)
8Esecuzione
1. Il server riconosce dallURl che la risorsa
richiesta dal cliente e un eseguibile
9Esecuzione
2. Il server decodifica i parametri inviati dal
cliente e riempie le variabili dambiente es
request_method, query_string, content_length,
content_type
10Esecuzione
3. Il server lancia in esecuzione lapplicazione
richiesta
11Esecuzione
4. Lapplicazione stampa la sua risposta sullo
standard output
12Esecuzione
5. Il server ridireziona lo standard output sulla
rete e quindi verso il client
13Invio di parametri a un programma CGI
- Il client puo usare due metodi
- GET
- POST
- GET i parametri sono codificati
nellURLhttp//www.mioserver.it/cgi-bin/xyz?parv
al - POST i parametri sono spediti al server
separatamente, usando il body del messaggio di
richiesta HTTP - NB il metodo POST richiede luso di un costrutto
HTML chiamato FORM
14FORM HTML
Esempio invio al server il nome dellutente
ltform actionhttp//www.mysrvr.it/cgi-bin/xyz.e
xe methodpostgt ltpgtDimmi il tuo nome ltinput
typetext namechisei gtlt/pgt ltinput typesubmit
gt lt/formgt
15FORM HTML
16Struttura di un programma CGI
leggi le variabili dambiente
elabora
stampa intestazione MIME
Content-type text/html
17Decodifica dei parametri
leggi la variabile Request_method
18Revisione critica di HTTP
- HTTP non prevede metodi per identificare lutente
- Ogni richiesta è trattata come un evento isolato
- Una nuova richiesta non ricorda nulla della
precedente - Non esiste il concetto di sessione interattiva
dellutente - Impossibile fare applicazioni personalizzate
19Revisione critica di CGI
- Il web server genera un nuovo processo cgi ad
ogni richiesta - Il processo viene terminato alla fine del computo
della risposta - Altissimo sovraccarico di esecuzione per la
creazione e distruzione di processi - Impossibile
- Tenere informazioni sulla sessione dellutente in
memoria centrale (serve un database) - Tenere allocate risorse condivise tra più
richieste o più utenti (es. pool di connessioni a
database)
20Web Database AccessRequest
Web Server
http//server/scripts/dbprog.exe?lnameSmith
Input URL with program and parameters,
e.g. http//server/scripts/dbprog.exe?lnameSmith
Web Browsers
21Web Database AccessWeb Server launches program
Web Server
Database Program (e.g. dbprog.exe)
http//server/scripts/dbprog.exe?lnameSmith
- Web Server launches database program named in URL
(dbprog.exe) - Can be either CGI (EXE, perl script) or
ISAPI/NSAPI (DLL, shared lib) - Program reads HTTP headers to get any parameters
(lname Smith in this example)
Web Browsers
22Web Database AccessProgram uses database API to
connect to DBMS
Web Server
Database API (ODBC, native)
API
Database Program
- Program uses some database API to access the
database (ODBC, Oracle OCI, Sybase CT-Lib, etc.) - Uses web browser form inputs and HTTP headers to
parameterize SQL (e.g. select from customer
where lnamelname)
Web Browsers
23Web Database AccessSQL statement sent to DBMS
Web Server
Database API (ODBC, native)
Database
API
Database Program
SQL
Database API library sends SQL statement to the
DBMS (SQL Server, Oracle, Informix)
Web Browsers
24Web Database AccessDBMS returns results to
program
Web Server
Database API (ODBC, native)
Database
API
Database Program
SQL
Results
CGI/ISAPI program retrieves data via Database API
Web Browsers
25Web Database AccessProgram merges results with
HTML sends to client
Web Server
Database API (ODBC, native)
Database
API
Database Program
SQL
HTML with merged results
Results
- Database program merges results with HTML,
producing an HTML document - Web Server transmits to client web browser
Web Browsers
26Adding HTML to code or coding in HTML?
Web Server
Database API (ODBC, native)
Database
API
Database Program
SQL
HTML with merged results
Results
Q Where is the HTML? A Embedded in C/C/perl
code!
Web Browsers
27Adding HTML to code or coding in HTML?
- HTML embedded in C/C is bad news
- Editing is hard no WYSIWYG
- Skill level for building web application requires
C/C/Perl programmer - Cant leverage growing toolset for HTML editing
- But, get full power of language for controlling
content and database access - One Solution create a hybrid
- Invent new kind of HTML document a template
- HTML contains special tags which are processed by
CGI/ISAPI application - Application semantics are moved from the
CGI/ISAPI application to the template - CGI/ISAPI application becomes a template
processor
28Adding HTML to code or coding in HTML?
ltHTMLgt ltBODYgt ltDBTAG1gt ltDBTAG2gt lt/BODYgt lt/HTMLgt
Database
Web Server
Database API (ODBC, native)
API
Database Program
SQL
HTML with merged results
Results
Q Where is the HTML? A Embedded in template
29Adding HTML to code or coding in HTML?
- Examples of HTML templates
- Allaire Cold Fusion
- Nomad WebDBC
- Microsoft IIS Database Connector
- Many others....
- Issues
- Most have special tags for control flow, looping,
database access - Is this the start of a new programming
language??? - Adding HTML to code or coding in HTML?
- HTML centric view is nice, but....................
- Adding new tags to enhance programmability new
programming language - Wouldnt it be nice to use a programming language
you already know with HTML?
30Una alterantiva
- Embed existing programming language with HTML,
such as Visual Basic - dbWeb
- Haht Software
- Allow full intermixing of VB and HTML
- Extensibility via VB OLE and other Libraries
(OLEdb)
31Obiettivi delle architetture server side
- Migliori prestazioni creare processi solo in
fase di inizializzazione del sistema e riusare un
pool di processi pronti - Mantenimento dello stato sfruttare la
persistenza del processo per mantenere
informazioni sulla sessione dellutente (stateful
application) - Condivisione delle risorse mantenere allocate le
risorse condivise - Scalabilità aumentare il numero di processi
applicativi allaumentare del traffico
32Architetture application server
33Java Servlet http//java.sun.com/products/servlet
/index.html
HTTP Request
parametri
risposta
HTTP Response
Browser
- Servlet container un programma Java che fornisce
un ambiente persistente di esecuzione per
applicazioni Web ed espone le caratteristiche del
Web server come oggetti Java - Servlet lanalogo di uno script CGI nel mondo
Java
34Esempio di servlet
- import java.io.
- import javax.servlet.
- import javax.servlet.http.
- public class RequestInfo extends HttpServlet
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException,
ServletException response.setContentType("text
/html") PrintWriter out response.getWriter()
out.println("ltHTMLgt") out.println("ltHEADgt")
out.println("ltTITLEgtRequest Information
Examplelt/TITLEgt") out.println("lt/HEADgt")
out.println("ltBODYgt") out.println("ltH3gtRequest
Information Examplelt/H3gt") out.println("Method
" request.getMethod()) out.println("ltBRgt")
out.println("Request URI "
request.getRequestURI()) out.println("ltBRgt")
out.println("User Agent"request.getHeader("User
-Agent")) out.println("lt/BODYgt")
out.println("lt/HTMLgt")
35Risultato
36Classi/interfacce di utilità
- HTTPServletRequest
- METODI getHeader(), getMethod(),
getQueryString(),.. - HTTPServletResponse
- METODI getWriter(), setContentLenght,
setContenType(), setHeader(), setStatus(), .. - HTTPSession
- METODI getAttribute(), invalidate(), isNew,
setMaxInactiveInterval() - Cookie
- METODI setValue(), GetValue(), getName(),
setMaxAge(),..
37Valutazione
- Astrazione object-oriented delle proprietà di un
server HTTP esteso (request, response, session
ecc) - Programmazione complessa perchè bisogna produrre
sia il testo statico che i contenuti dinamici - La presentazione HTML è mescolata al codice
applicativo - Esigenza serve una soluzione più semplice per
produrre pagine in modo dinamico a lato server
38Server-side scripting
- Idea inserire istruzioni per il calcolo dei
contenuti dinamici allinterno della pagina HTML - Il codice è interpretato dal server
- Il browser riceve HTML puro
39Active server page ASP ADO
40ADO and WEB
41Active Server Page - ASP
42ASP Server Framework
- ASP Server Scripting
- Hosts VB Script natively
- Perl, JavaScript also supported
- Enables scripting of ASP Server Controls
- ASP Server Controls
- Built on standard tools VB, VC/C, Java
- Objects compatible w/ OLE Automation hosts
- Database connectivity is native
- Via OLEdb - ADO
43ADO and VBScript an example
- Prepare the form
- lthmtlgt tags and intrinsic objects lt/hmtlgt
- Get a recordset
- ltobject idrs classid."gtlt/objectgt
- ltscript language"VBScript"gt Provider, DataSource
- rs.open .
- View the data
- HTMLObject.Text rs.Fields().Value
- Data Browsing
- rs.MoveNext, rs.MovePrevious
44An example of data access -DEMO
- An MDB file (MS Access)
- No registration, no DSN definition, no
declaration - Only two components (plus the browser)
Middle tier
Data tier
User tier
Data Access
Run Query
Data Base
Multi scroll
Call SP
45Java Server Pages (JSP)
- JSP è una architettura per server-side scripting
proposta da Sun (come alternativa a ASP di
Microsoft) - Si fonda su tecnologia Java linguaggio Java,
Java Servlet, Java Beans - Cronologia
- Proposta presentata a JavaOne 98
- Versione 0.92 revisione pubblica conclusa a
Genn. 99 - Versione 1.0 disponibile 1Q 99
- Versione 1.1 disponibile 1Q 00
- Versione 1.2 in uso da ottobre 2001
46File JSP
- Un file .asp contiene una combinazione di
- Testo
- Tag HTML
- Istruzioni di server-side scripting
- E necessario disporre di un ambiente di
compilazione apposito (ad es. Tomcat di Apache
Jakarta)
47Procedure ed espressioni
- Scriptlets
- procedure racchiuse tra delimitatori (lt.gt)
scritte in Java - Espressioni
- Unespressione ha la formalt variablegt La
variabile viene valutata e il valore risultante,
convertito in stringa, viene inserito nella
pagina al posto dellespressione
48Direttive
- Direttive lt_at_ variablevalue gt
- il tipo di linguaggio da utilizzare allinterno
del file JSP (lt_at_ languagejavagt) - il file .jsp o .html che viene ritornato al
client se lesecuzione della pagina JSP
restituisce un errore (lt_at_ errorepagecontactweb
master.htmlgt) - i moduli (packages) importati dagli oggetti
usati nella pagina (lt_at_ importjava.io.,
java.util.Hashtablegt)
49Esempio
- ltHTMLgtltHEADgtltTITLEgtRequest Information
Examplelt/TITLEgtlt/HEADgtltBODYgtltH3gtRequest
Information Examplelt/H3gtMethod lt
request.getMethod() gt ltBRgtRequest URI lt
request.getRequestURI() gt ltBRgtUser Agent lt
request.getHeader("User-Agent") gt lt/BODYgt - lt/HTMLgt
Risultato la stessa pagina computata dal servlet
mostrato in precedenza
50Compilazione
- Il file JSP viene prima tradotto in un servlet
- Il servlet viene compilato in bytecode
- La versione compilata viene tenuta in memoria per
rendere più veloce una successiva richiesta della
pagina - NB La versione originaria di Microsoft ASP (non
ASP.NET) non compilava i template
51Valutazione
- Indipendenza dal tipo di browser utilizzato
- Il browser vede solamente pagine HTML
- Allutente non sono necessari programmi
proprietari o estensioni del browser - Maggior facilità di apprendimento e utilizzo
rispetto a servlet - Oggetti di utilità
- Nasconde la presenza di programmi script agli
utenti e ad eventuali hacker - Resta però codice (anche se poco) frammisto a
markup HTML
52Tag eseguiti a lato server
- Obiettivo togliere il codice dai template di
pagina - Soluzione nascondere il codice dietro tag
magici, eseguiti dal server
lt_at_ taglib uri"http//www.myserver.com/mytaglib"
prefixmytag" gt ltHTMLgt ltHEADgtltTITLEgtEsempio di
tag iteratorelt/TITLEgtlt/HEADgtltBODYgtltmytagiterato
re att1un att2due att3tre!gt
ltpgtltmytagelementogtlt/pgtlt/mytagiteratoregt
lt/BODYgt lt/HTMLgt
53Risultato
54ASP .NET
55Overview
- Originally Active Server Pages (ASP)
- ASP.NET
- Successor of ASP
- Different paradigm (.NET Framework)
- Topics
- Stateless web paradigm
- Code behind pages
- Response and Request objects
- Session and Application variables
56Stateless web paradigm
- Client may return to any page at any time in any
state - State information is posted during each page
request (?xxxxxxxxxx) - ASP.NET web controls automatically repost their
own state to maintain the ViewState of the page
57Code behind pages
- Binds HTML page to a code file written in a .NET
language - HTML page is encapsulated in a System.Web.UI.Page
class - Events such as Page_Load may be handled
- All ASP.NET controls can be used as regular .NET
objects - Scripts in HTML page may call code behind
functions - Everything will eventually end up as HTML
58Response and Request objects
- Response
- Represents the client browser
- Response.Redirect(http//www.microsoft.com)
- Response.CookiesUserName Bob
- Request
- Represents the server
- Request.PhysicalApplicationPath
- UserName (String)Request.CookiesUserName
59Session and Application variables
- Session variables
- Hashtable-style collection of name-value pairs
- Remembered until the client closes the browser
(or the session timeout expires default 20
minutes) - Only for one client
- SessionValidUser true
- Application variables
- Hashtable-style collection of name-value pairs
- Always remembered
- For all clients
- ApplicationNumClients NumClients 1
60Riferimenti
- CGI http//hoohoo.ncsa.uiuc.edu/cgi/
- Java Servlet http//java.sun.com/products/servlet
/index.html - JSP http//java.sun.com/products/jsp/index.html
- .NET http//samples.gotdotnet.com/quickstart/aspp
lus/