Tecnologie lato Server JSP Java Server Pages Stefano
- Slides: 129
Tecnologie lato Server: JSP (Java Server Pages) Stefano Clemente s. clemente@ei. unibo. it © 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 6 Dicembre 2005 Wide Web – How To Program (Second Edition) Stefano Clemente
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 31 (sul CD allegato al libro) • http: //java. sun. com/developer/online. Tra ining/JSPIntro/contents. html • http: //jakarta. apache. org 6 Dicembre 2005 Stefano Clemente 2
Introduzione • JSP sono formate da − componenti HTML e XML − appositi tag JSP − parti opzionali di codice Java dette “scriptlet” • JSP estende l’API servlet • Differenze tra JSP e Servlet − Le Servlet è una tecnologia di programmazione che richiede esperienza nella programmazione − JSP si rivolgono a un “pubblico” più ampio, in quanto utilizzabili sia dagli sviluppatori che dai disegnatori di pagine 6 Dicembre 2005 Stefano Clemente 3
Introduzione • Separazione del contenuto statico da quello dinamico − Con JSP la logica della generazione del contenuto dinamico è separata dalle parti statiche attraverso l’uso di componenti Java. Beans; queste componenti vengono create e usate dalle pagine JSP attraverso tag ad hoc e scriptlet e ogni modifica alla pagina JSP comporta la ricompilazione automatica della pagina e il ricamento nel web server da parte dello stesso motore JSP • Write Once Run Anywhere − La tecnologia JSP usa questo paradigma per le pagine interattive; le pagine JSP possono essere portate su varie piattaforme e web server senza modifiche 6 Dicembre 2005 Stefano Clemente 4
Introduzione • Il contenuto dinamico può essere inviato in vari formati − Le JSP possono essere richieste da vari client • • Browser Cellulari PDA Applicazioni B 2 B che fanno uso di XML • Consigliate per applicazioni client/server a nlivelli • Sfruttano la potenza delle Servlet − Le JSP sono un’astrazione ad alto livello delle Servlet e consentono di fare tutto ciò che si può fare con le Servlet, ma in modo più semplice 6 Dicembre 2005 Stefano Clemente 5
Introduzione • Le Java. Server Pages (JSP) sono un’estensione della tecnologia Servlet • Sono progettate per semplificare l’invio di contenuti dinamici • Package addizionali − Package javax. servlet. jsp • Contiene la maggior parte delle classi e dei metodi di JSP − Package javax. servlet. jsp. tagtest • Contiene le classi e i metodi per i custom tag 6 Dicembre 2005 Stefano Clemente 6
Componenti di JSP • Direttive − Sono messaggi al JSP-Container che permettono di specificare • impostazioni della pagina • includere contenuti da altre risorse • specificare tag definiti dall’utente da utilizzare • Azioni − incapsulano funzionalità in tag predefiniti che il programmatore può inserire nella JSP − spesso eseguite in base alla richiesta inviata dal client − creano anche oggetti Java per le Scriptlets • Scriptlets (SCRIPTing e. LEmen. TS) − permettono di inserire codice Java nelle JSP (e altre componenti dell’applicazione web) per eseguire la richiesta del client • Librerie di Tag − sono parte del meccanismi di estensione dei tag che permette al programmatore di creare dei propri tag 6 Dicembre 2005 Stefano Clemente 7
JSP o Servlets? • JSP − somigliano ai documenti XHTML − usati quando la maggior parte del contenuto è statico • Servlets − usate quando la maggior parte del contenuto è dinamico • JSP e Servlets sono intercambiabili • la prima volta che viene richiesta, una JSP è compilata in una Servlet • hanno lo stesso ciclo di vita − − − 6 Dicembre 2005 jsp. Init jsp. Service jsp. Destroy Stefano Clemente 8
Esempio 1 6 Dicembre 2005 Stefano Clemente 9
Esempio 1: clock. jsp <? xml version = "1. 0"? > <!DOCTYPE html PUBLIC "-//W 3 C//DTD XHTML 1. 0 Strict//EN" "http: //www. w 3. org/TR/xhtml 1/DTD/xhtml 1 -strict. dtd"> <!-- Fig. 10. 1: clock. jsp --> <html xmlns = "http: //www. w 3. org/1999/xhtml"> <head> <meta http-equiv = "refresh" content = "60" /> <title>A Simple JSP Example</title> <style type = "text/css">. big { font-family: helvetica, arial, sans-serif; font-weight: bold; font-size: 2 em; } </style> </head> 6 Dicembre 2005 Stefano Clemente 10
Esempio 1: clock. jsp <body> <p class = "big">Simple JSP Example</p> <table style = "border: 6 px outset; "> <tr> <td style = "background-color: black; "> <p class = "big" style = "color: cyan; "> <!-- JSP expression to insert date/time --> <%= new java. util. Date() %> </p> </td> </tr> </table> </body> Espressione JSP </html> 6 Dicembre 2005 Stefano Clemente 11
Esempio 1 6 Dicembre 2005 Stefano Clemente 12
Oggetti Impliciti • Gli Oggetti Impliciti forniscono ai programmatori la possibilità di accedere a molte proprietà delle Sevlet nel contesto però delle JSP • Gli Oggetti Impliciti hanno quattro tipi di portata − applicazione (application scope) • oggetti posseduti dal JSP/Servlet Container manipolabili da Servlet e Applicazioni − pagina (page scope) • sono gli oggetti che esistono solo nella pagina che li definisce e che vengono istanziati ad ogni richiesta di quella pagina − richiesta (request scope) • sono gli oggetti che esistono solo per la durata di una richiesta (es. una richiesta che per essere soddisfatta richiama più Servlet) − sessione (session scope) • oggetti che esistono per l’intera durata di una sessione di navigazione di un client 6 Dicembre 2005 Stefano Clemente 13
Oggetti Impliciti 6 Dicembre 2005 Stefano Clemente 14
Scripting • Permette di inserire del codice Java nelle pagine JSP aggiungendo così contenuti dinamici • Componenti − Scriptlets (Script Elements) • Delimitati da <% e %> • Blocchi di codice Java − Commenti • Commenti Scriptlet delimitati da / e / • Commenti JSP delimitati da <%-- e --%> • Commenti XHTML delimitati da <!-- e --> − Espressioni • Delimitate da <%= and %> • Risultati convertiti in oggetti String 6 Dicembre 2005 Stefano Clemente 15
Scripting • … Componenti − Dichiarazioni • Delimitate da <%! e %> • Definiscono variabili e metodi • Richiedono il ; finale − Sequenze di Escape • Permettono di visualizzare nella risposta al client le sequenze di caratteri usate come solitamente come delimitatori − − − 6 Dicembre 2005 <% %/> ’ ” \ Stefano Clemente 16
Esempio 2 6 Dicembre 2005 Stefano Clemente 17
Esempio 1: welcome. jsp <? xml version = "1. 0"? > <!DOCTYPE html PUBLIC "-//W 3 C//DTD XHTML 1. 0 Strict//EN" "http: //www. w 3. org/TR/xhtml 1/DTD/xhtml 1 -strict. dtd"> <!-- Fig. 10. 4: welcome. jsp --> <!-- JSP that processes a "get" request containing data. --> <html xmlns = "http: //www. w 3. org/1999/xhtml"> <!-- head section of document --> <head> <title>Processing "get" requests with data</title> </head> <!-- body section of document --> <body> <% // begin scriptlet String name = request. get. Parameter( "first. Name" ); if ( name != null ) { %> <%-- end scriptlet to insert fixed template data --%> <h 1> Hello <%= name %>, 6 Dicembre 2005 Stefano Clemente 18
Esempio 1: welcome. jsp Welcome to Java. Server Pages! </h 1> <% // continue scriptlet } // end if else { %> <%-- end scriptlet to insert fixed template data --%> <form action = "welcome. jsp" method = "get"> <p> Type your first name and press Submit</p> <p><input type = "text" name = "first. Name" /> <input type = "submit" value = "Submit" /> </p> </form> <% // continue scriptlet } // end else %> <%-- end scriptlet --%> </body> </html> <!-- end XHTML document --> 6 Dicembre 2005 Stefano Clemente 19
Azioni Standard • Permettono di eseguire alcune tra le più comuni azioni eseguite in JSP − Inclusione dei contenuti di un’altra risorsa − Inoltro di richieste di altre risorse − Interazione con i Java. Beans • Sono elaborate dal JSP Container al momento della richiesta della risorsa • Sono delimitate dai tag <jsp: action> e </jsp: action> − Nel caso in cui non vi fosse niente da includere tra il tag di inizio e quello di chiusura si può usare <jsp: action /> 6 Dicembre 2005 Stefano Clemente 20
Azioni Standard 6 Dicembre 2005 Stefano Clemente 21
<jsp: include> • JSP fornisce due tipi di meccanismi di inclusione − Azione <jsp: include> • Permette che contenuti dinamici siano inclusi in una risorsa • Se il contenuto della risorsa inclusa cambia tra due richieste, sarà incluso nella prossima richiesta della JSP contenente l’azione <jsp: include> − Direttiva include • Include la risorsa una sola volta, vale a dire nel momento della traduzione della JSP • Se la risorsa inclusa cambia, il nuovo contenuto non si riflette nella JSP a meno di ricompilazione di quest’ultima 6 Dicembre 2005 Stefano Clemente 22
<jsp: include> • Attributi di <jsp: include> − page • Specifica la URI della risorsa da includere • La risorsa deve essere parte della stessa applicazione − flush • Specifica se il buffer deve essere ripulito dopo l’esecuzione dell’inclusione • In JSP 1. 1 questo attributo deve valere true 6 Dicembre 2005 Stefano Clemente 23
Esempio 3 • Viene mostrato l’uso dell’azione <jsp: include> attraverso l’inclusione di contenuti sia statici sia dinamici • Il documento include. jsp include tre altri documenti − banner. html − toc. html − clock 2. jsp • In particolare include. jsp è una tabella che: − nella parte alta mostra banner. html − a sinistra mostra toc. html − a destra mostra clock 2. jsp 6 Dicembre 2005 Stefano Clemente 24
Esempio 3 6 Dicembre 2005 Stefano Clemente 25
Esempio 3: banner. html <!-- banner to include in another document --> <div style = "width: 580 px"> <p> Java(TM), C, C++, Visual Basic(R), Object Technology, and Internet and World Wide Web Programming Training On-Site Seminars Delivered Worldwide </p> <a href = "mailto: deitel@deitel. com"> deitel@deitel. com</a> 978. 579. 9911 490 B Boston Post Road, Suite 200, Sudbury, MA 01776 </p> </div> 6 Dicembre 2005 Stefano Clemente 26
Esempio 3: toc. html <!-- contents to include in another document --> <p><a href = "http: //www. deitel. com/books/index. html"> Publications/Book. Store </a></p> <p><a href = "http: //www. deitel. com/whatsnew. html"> What's New </a></p> <p><a href = "http: //www. deitel. com/books/downloads. html"> Downloads/Resources </a></p> <p><a href = "http: //www. deitel. com/faq/index. html"> FAQ (Frequently Asked Questions) </a></p> <p><a href = "http: //www. deitel. com/intro. html"> Who we are </a></p> <p><a href = "http: //www. deitel. com/index. html"> Home Page </a></p> <p>Send questions or comments about this site to <a href = "mailto: deitel@deitel. com"> deitel@deitel. com </a> Copyright 1995 -2002 by Deitel & Associates, Inc. All Rights Reserved. </p> 6 Dicembre 2005 Stefano Clemente 27
Esempio 3: clock 2. jsp <!-- Fig. 10. 9: clock 2. jsp --> <!-- date and time to include in another document --> <table> <tr> <td style = "background-color: black; "> <p class = "big" style = "color: cyan; font-size: 3 em; font-weight: bold; "> <%= new java. util. Date() %> </p> </td> </tr> </table> 6 Dicembre 2005 Stefano Clemente 28
Esempio 3: include. jsp <? xml version = "1. 0"? > <!DOCTYPE html PUBLIC "-//W 3 C//DTD XHTML 1. 0 Strict//EN" "http: //www. w 3. org/TR/xhtml 1/DTD/xhtml 1 -strict. dtd"> <!-- Fig. 10. 7: include. jsp --> <html xmlns = "http: //www. w 3. org/1999/xhtml"> <head> <title>Using jsp: include</title> <style type = "text/css"> body { font-family: tahoma, helvetica, arial, sansserif; } 6 Dicembre 2005 Stefano Clemente 29
Esempio 3: include. jsp table, tr, td { font-size: . 9 em; border: 3 px groove; padding: 5 px; background-color: #dddddd; } </style> </head> <body> <table> <tr> <td style = align: center"> <img src width 6 Dicembre 2005 "width: 160 px; text= "images/logotiny. png" = "140" height = "93" Stefano Clemente 30
Esempio 3: include. jsp /> alt = "Deitel & Associates, Inc. Logo" </td> <%-- include banner. html in this JSP --%> <jsp: include page = "banner. html" flush = "true" /> </td> </tr> <td style = "width: 160 px"> 6 Dicembre 2005 Stefano Clemente 31
Esempio 3: include. jsp "true" /> <%-- include toc. html in this JSP --%> <jsp: include page = "toc. html" flush = </td> <td style = "vertical-align: top"> <%-- include clock 2. jsp in this JSP --%> <jsp: include page = "clock 2. jsp" flush = "true" /> </td> </tr> </table> </body> </html> 6 Dicembre 2005 Stefano Clemente 32
<jsp: forward> • Permette di inoltrare una richiesta a un’altra risorsa • La richiesta alla pagina JSP originaria contenente l’azione <jsp: forward> termina non appena viene inoltrata la richiesta • <jsp: forward> ha solo un attributo page che specifica l’URI della risorsa (all’interno della stessa applicazione) 6 Dicembre 2005 Stefano Clemente 33
Esempio 4 6 Dicembre 2005 Stefano Clemente 34
Esempio 4: forward 1. jsp <? xml version = "1. 0"? > <!DOCTYPE html PUBLIC "-//W 3 C//DTD XHTML 1. 0 Strict//EN" "http: //www. w 3. org/TR/xhtml 1/DTD/xhtml 1 -strict. dtd"> <!-- Fig. 10. 11: forward 1. jsp --> <html xmlns = "http: //www. w 3. org/1999/xhtml"> <head> <title>Forward request to another JSP</title> </head> <body> <% // begin scriptlet String name = request. get. Parameter( "first. Name" ); if ( name != null ) { %> <%-- end scriptlet to insert fixed template data --%> <jsp: forward page = "forward 2. jsp"> <jsp: param name = "date" value = "<%= new java. util. Date() %>" /> </jsp: forward> 6 Dicembre 2005 Stefano Clemente 35
Esempio 4: forward 1. jsp <% // continue scriptlet } // end if else { %> <%-- end scriptlet to insert fixed template data --%> <form action = "forward 1. jsp" method = "get"> <p>Type your first name and press Submit</p> <p><input type = "text" name = "first. Name" /> <input type = "submit" value = "Submit" /> </p> </form> <% // continue scriptlet } // end else %> <%-- end scriptlet --%> </body> </html> <!-- end XHTML document --> 6 Dicembre 2005 Stefano Clemente 36
Esempio 4: forward 2. jsp <? xml version = "1. 0"? > <!DOCTYPE html PUBLIC "-//W 3 C//DTD XHTML 1. 0 Strict//EN" "http: //www. w 3. org/TR/xhtml 1/DTD/xhtml 1 -strict. dtd"> <!-- forward 2. jsp --> <html xmlns = "http: //www. w 3. org/1999/xhtml"> <head> <title>Processing a forwarded request</title> <style type = "text/css">. big { font-family: tahoma, helvetica, arial, sansserif; font-weight: bold; font-size: 2 em; } </style> </head> 6 Dicembre 2005 Stefano Clemente 37
Esempio 4: forward 2. jsp <body> <p class = "big"> Hello <%= request. get. Parameter( "first. Name" ) %>, Your request was received and forwarded at </p> <table style = "border: 6 px outset; "> <tr> <td style = "background-color: black; "> <p class = "big" style = "color: cyan; "> <%= request. get. Parameter( "date" ) %> </p> </td> </tr> </table> </body> </html> 6 Dicembre 2005 Stefano Clemente 38
<jsp: param> • Permette di specificare coppie di parametri nome/valore da passare alle azioni − <jsp: include> − <jsp: forward> − <jsp: plugin> • <jsp: param> ha due attributi: − name che specifica il nome del parametro − value che specifica il valore del parametro • Se <jsp: param> specifica un parametro già esistente nella richiesta, il valore passato con essa ha precedenza su quello della richiesta 6 Dicembre 2005 Stefano Clemente 39
Esempio 5 6 Dicembre 2005 Stefano Clemente 40
Esempio 5: forward 3. jsp <? xml version = "1. 0"? > <!DOCTYPE html PUBLIC "-//W 3 C//DTD XHTML 1. 0 Strict//EN" "http: //www. w 3. org/TR/xhtml 1/DTD/xhtml 1 -strict. dtd"> <!-- Fig. 10. 11: forward 3. jsp --> <html xmlns = "http: //www. w 3. org/1999/xhtml"> <head> <title>Forward request to another JSP</title> </head> <body> <% // begin scriptlet String name = request. get. Parameter( "first. Name" ); if ( name != null ) { %> <%-- end scriptlet to insert fixed template data --%> <jsp: forward page = "forward 2. jsp"> <jsp: param name = "first. Name" value = "Pippo" /> <jsp: param name = "date" value = "<%= new java. util. Date() %>" /> </jsp: forward> 6 Dicembre 2005 Stefano Clemente 41
Esempio 5: forward 3. jsp <% // continue scriptlet } // end if else { %> <%-- end scriptlet to insert fixed template data --%> <form action = "forward 3. jsp" method = "get"> <p>Type your first name and press Submit</p> <p><input type = "text" name = "first. Name" /> <input type = "submit" value = "Submit" /> </p> </form> <% // continue scriptlet } // end else %> <%-- end scriptlet --%> </body> </html> <!-- end XHTML document --> 6 Dicembre 2005 Stefano Clemente 42
Esempi 4 e 5: File 6 Dicembre 2005 Stefano Clemente 43
<jsp: plugin> • Permette di aggiungere Applet o Java. Bean a una pagina sotto forma di un oggetto specifico del browser o di un elemento XHTML embed − Applet = … (v. gruppo di lucidi Tecn. Int 8. pdf) − Java. Bean = componente software riutilizzabile manipolabile in modo visuale attraverso dei tool per costruzione software Java, es. • semplici elementi GUI come i bottoni • componenti software visuali come visualizzatori di DB o fogli di dati • elementi senza nessuna apparenza grafica, ma che possono essere composti insieme in modo visuale attraverso degli “application builder” 6 Dicembre 2005 Stefano Clemente 44
<jsp: plugin> • L’azione abilita il client al download e all’installazione del plug-in nel caso questo non lo avesse già 6 Dicembre 2005 Stefano Clemente 45
Esempio 6 Applet 6 Dicembre 2005 Stefano Clemente 46
Esempio 6: Shapes. Applet. java // Fig. 10. x: Shapes. Applet. java // Applet that demonstrates a Java 2 D General. Path. package advjhtp 1. jsp. applet; // Java core packages import java. applet. *; import java. awt. event. *; import java. awt. geom. *; // Java extension packages import javax. swing. *; public class Shapes. Applet extends JApplet { // initialize the applet public void init() { // obtain color parameters from XHTML file 6 Dicembre 2005 Stefano Clemente 47
Esempio 6: Shapes. Applet. java try { int red = Integer. parse. Int( get. Parameter( "red" ) ); int green = Integer. parse. Int( get. Parameter( "green" ) ); int blue = Integer. parse. Int( get. Parameter( "blue" ) ); Color background. Color = new Color( red, green, blue ); } set. Background( background. Color ); // if there is an exception // parameters, catch it and catch ( Exception exception // do nothing } } while processing the color ignore it ) { public void paint( Graphics g ) { 6 Dicembre 2005 Stefano Clemente 48
Esempio 6: Shapes. Applet. java // create arrays of x and y coordinates int x. Points[] = { 55, 67, 109, 73, 83, 55, 27, 37, 1, 43 }; int y. Points[] = { 0, 36, 54, 96, 72, 96, 54, 36 }; // obtain reference to a Graphics 2 D object Graphics 2 D g 2 d = ( Graphics 2 D ) g; // create a star from a series of points General. Path star = new General. Path(); // set the initial coordinate of the General. Path star. move. To( x. Points[ 0 ], y. Points[ 0 ] ); // create the star--this does not draw the star for ( int k = 1; k < x. Points. length; k++ ) star. line. To( x. Points[ k ], y. Points[ k ] ); 6 Dicembre 2005 Stefano Clemente 49
Esempio 6: Shapes. Applet. java // close the shape star. close. Path(); // translate the origin to (200, 200) g 2 d. translate( 200, 200 ); // rotate around origin and draw stars in random colors for ( int j = 1; j <= 20; j++ ) { g 2 d. rotate( Math. PI / 10. 0 ); g 2 d. set. Color( new Color( ( } } } 6 Dicembre 2005 int int g 2 d. fill( star ); ) ) ) ( ( ( Math. random() * * * 256 256 ), ), ) ) ); // draw a filled star Stefano Clemente 50
Esempio 6: plugin. jsp <html> <head> <title>Using jsp: plugin to load an applet</title> </head> <body> <jsp: plugin type = "applet" code = "com. deitel. advjhtp 1. jsp. applet. Shapes. Applet" codebase = "/advjhtp 1/jsp" width = "400" height = "400"> <jsp: params> <jsp: param </jsp: params> name = = = "red" value = "255" /> "green" value = "255" /> "blue" value = "0" /> </jsp: plugin> </body> </html> 6 Dicembre 2005 Stefano Clemente 51
Esempio 6 6 Dicembre 2005 Stefano Clemente 52
Esempio 6: File JSP 6 Dicembre 2005 Stefano Clemente 53
Esempio 6: File Applet (Plug-in) 6 Dicembre 2005 Stefano Clemente 54
<jsp: usebean> • Permette alle JSP di manipolare degli oggetti Java • L’azione crea un oggetto o ne individua uno esistente per l’uso nella JSP 6 Dicembre 2005 Stefano Clemente 55
<jsp: usebean> • Se non vengono specificati gli attributi class e bean. Name, bean. Name il JSP-container cerca di individuare un oggetto del tipo specificato con l’attributo type • Proprio come gli oggetti impliciti, gli oggetti specificati con <jsp: usebean> hanno portate dei tipi page, page request, request session, session application − gli oggetti con portata di tipo page possono essere acceduti solo nella JSP in cui sono definiti − più JSP possono accedere gli oggetti con i restanti tipi di portata 6 Dicembre 2005 Stefano Clemente 56
Esempio 7 6 Dicembre 2005 Stefano Clemente 57
Esempio 7: Rotator. java(Bean) // Fig. 10. 17: Rotator. java // A Java. Bean that rotates advertisements. package com. deitel. advjhtp 1. jsp. beans; public class Rotator { private String images[] = { "images/jhtp 3. jpg", "images/xmlhtp 1. jpg", "images/ebechtp 1. jpg", "images/iw 3 htp 1. jpg", "images/cpphtp 3. jpg"}; private String links[] = { "http: //www. amazon. com/exec/obidos/ASIN/0130125075/" "deitelassociatin", "http: //www. amazon. com/exec/obidos/ASIN/0130284173/" "deitelassociatin", "http: //www. amazon. com/exec/obidos/ASIN/013028419 X/" "deitelassociatin", "http: //www. amazon. com/exec/obidos/ASIN/0130161438/" "deitelassociatin", "http: //www. amazon. com/exec/obidos/ASIN/0130895717/" "deitelassociatin" }; 6 Dicembre 2005 Stefano Clemente + + + 58
Esempio 7: Rotator. java(Bean) private int selected. Index = 0; // returns image file name for current ad public String get. Image() { return images[ selected. Index ]; } // returns the URL for ad's corresponding Web site public String get. Link() { return links[ selected. Index ]; } } // update selected. Index so next calls to get. Image and // get. Link return a different advertisement public void next. Ad() { selected. Index = ( selected. Index + 1 ) % images. length; } 6 Dicembre 2005 Stefano Clemente 59
Esempio 7: adrotator. jsp <? xml version = "1. 0"? > <!DOCTYPE html PUBLIC "-//W 3 C//DTD XHTML 1. 0 Strict//EN" "http: //www. w 3. org/TR/xhtml 1/DTD/xhtml 1 -strict. dtd"> <!-- Fig. 10. 18: adrotator. jsp --> <jsp: use. Bean id = "rotator" scope = "session" class = "com. deitel. advjhtp 1. jsp. beans. Rotator" /> <html xmlns = "http: //www. w 3. org/1999/xhtml"> <head> <title>Ad. Rotator Example</title> <style type = "text/css">. big { font-family: helvetica, arial, sansserif; font-weight: bold; font-size: 2 em; } 6 Dicembre 2005 Stefano Clemente 60
Esempio 7: adrotator. jsp </style> <%-- update advertisement --%> <% rotator. next. Ad(); %> </head> <body> <p class = "big">Ad. Rotator Example</p> <a href = "<jsp: get. Property name = "rotator" property = "link" />"> <img src = "<jsp: get. Property name = "rotator" property = "image" />" alt = "advertisement" /> </a> </p> </body> </html> 6 Dicembre 2005 Stefano Clemente 61
Esempio 7: adrotator 1. jsp </style> <%-- update advertisement --%> <% rotator. next. Ad(); %> </head> <body> <p class = "big">Ad. Rotator Example</p> <a href = "<%= rotator. get. Link() %>"> <img src = "<%= rotator. get. Image() %>" alt = "advertisement" /> </a> </p> </body> </html> 6 Dicembre 2005 Stefano Clemente 62
Esempio 7: File JSP 6 Dicembre 2005 Stefano Clemente 63
Esempio 7: File Java. Bean (Plug-in) 6 Dicembre 2005 Stefano Clemente 64
<jsp: get. Property> • Serve per ottenere valori dal bean • Ha due attributi − − name – il nome del bean property – la proprietà da recuperare • Quando il JSP-container incontra <jsp: get. Property name = "abc" property = "xyz" /> cerca di invocare get. Xyz dall’oggetto abc • Equivale a scrivere l’espressione JSP <%= abc. get. Xyz() %> 6 Dicembre 2005 Stefano Clemente 65
<jsp: set. Property> • Serve per settare valori nel bean 6 Dicembre 2005 Stefano Clemente 66
Esempio 8 1 2 6 Dicembre 2005 Stefano Clemente 67
Esempio 8: Guest. Bean. java // Fig. 10. 20: Guest. Bean. java // Java. Bean to store data for a guest in the guestbook. package com. deitel. advjhtp 1. jsp. beans; public class Guest. Bean { private String first. Name, last. Name, email; // set the guest's first name public void set. First. Name( String name ) { first. Name = name; } // get the guest's first name public String get. First. Name() { return first. Name; } // set the guest's last name public void set. Last. Name( String name ) 6 Dicembre 2005 Stefano Clemente 68
Esempio 8: Guest. Bean. java { } last. Name = name; // get the guest's last name public String get. Last. Name() { return last. Name; } // set the guest's email address public void set. Email( String address ) { email = address; } } // get the guest's email address public String get. Email() { return email; } 6 Dicembre 2005 Stefano Clemente 69
Esempio 8: Guest. Data. Bean. java // Class Guest. Data. Bean makes a database connection and supports // inserting and retrieving data from the database. package com. deitel. advjhtp 1. jsp. beans; // Java core packages import java. io. *; import java. sql. *; import java. util. *; public class Guest. Data. Bean { private Connection connection; private Prepared. Statement add. Record, get. Records; // construct Titles. Bean object public Guest. Data. Bean() throws Exception { Class. for. Name("sun. jdbc. odbc. Jdbc. Odbc. Driver"); String filename = "c: /web/advjhtp 1/guestbook. mdb"; String database = "jdbc: odbc: Driver={Microsoft Access Driver " + "(*. mdb)}; DBQ="; database+= filename. trim() + "; Driver. ID=22; READONLY=true}"; 6 Dicembre 2005 Stefano Clemente 70
Esempio 8: Guest. Data. Bean. java connection = Driver. Manager. get. Connection( database , ""); get. Records = connection. prepare. Statement( "SELECT first. Name, last. Name, email FROM guests" ); add. Record = connection. prepare. Statement( "INSERT INTO guests ( " + "first. Name, last. Name, email ) " + "VALUES ( ? , ? )" ); } // return an Array. List of Guest. Beans public List get. Guest. List() throws SQLException { List guest. List = new Array. List(); // obtain list of titles 6 Dicembre 2005 Stefano Clemente 71
Esempio 8: Guest. Data. Bean. java Result. Set results = get. Records. execute. Query(); // get row data while ( results. next() ) { Guest. Bean guest = new Guest. Bean(); guest. set. First. Name( results. get. String( 1 ) ); guest. set. Last. Name( results. get. String( 2 ) ); guest. set. Email( results. get. String( 3 ) ); } } guest. List. add( guest ); return guest. List; // insert a guest in guestbook database public void add. Guest( Guest. Bean guest ) throws SQLException { add. Record. set. String( 1, guest. get. First. Name() ); add. Record. set. String( 2, guest. get. Last. Name() ); 6 Dicembre 2005 Stefano Clemente 72
Esempio 8: Guest. Data. Bean. java add. Record. set. String( 3, guest. get. Email() ); } add. Record. execute. Update(); // close statements and terminate database connection protected void finalize() { // attempt to close database connection try { get. Records. close(); add. Record. close(); connection. close(); } } } // process SQLException on close operation catch ( SQLException sql. Exception ) { sql. Exception. print. Stack. Trace(); } 6 Dicembre 2005 Stefano Clemente 73
Esempio 8: Guest. Book. Login. jsp <? xml version = "1. 0"? > <!DOCTYPE html PUBLIC "-//W 3 C//DTD XHTML 1. 0 Strict//EN" "http: //www. w 3. org/TR/xhtml 1/DTD/xhtml 1 -strict. dtd"> DIRETTIVA <!-- Fig. 10. 22: guest. Book. Login. jsp --> <%-- page settings --%> <%@ page error. Page = "guest. Book. Error. Page. jsp" %> <%-- beans used in this JSP --%> <jsp: use. Bean id = "guest" scope = "page" class = "com. deitel. advjhtp 1. jsp. beans. Guest. Bean" /> <jsp: use. Bean id = "guest. Data" scope = "request" class = "com. deitel. advjhtp 1. jsp. beans. Guest. Data. Bean" /> <html xmlns = "http: //www. w 3. org/1999/xhtml"> <head> <title>Guest Book Login</title> <style type = "text/css"> body { font-family: tahoma, helvetica, arial, sans-serif; } 6 Dicembre 2005 Stefano Clemente 74
Esempio 8: Guest. Book. Login. jsp table, tr, td { font-size: . 9 em; border: 3 px groove; padding: 5 px; background-color: #dddddd; } </style> </head> <body> <jsp: set. Property name = "guest" property = "*" /> <% // start scriptlet if ( guest. get. First. Name() == null || guest. get. Last. Name() == null || guest. get. Email() == null ) { %> <%-- end scriptlet to insert fixed template data --%> <form method = "post" action <p>Enter your first name, address to register in = "guest. Book. Login. jsp"> last name and email our guest book. </p> <table> <tr> 6 Dicembre 2005 Stefano Clemente 75
Esempio 8: Guest. Book. Login. jsp <td>First name</td> <input type = "text" name = "first. Name" /> </td> </tr> <td>Last name</td> <input type = "text" name = "last. Name" /> </td> </tr> <td>Email</td> <input type = "text" name = "email" /> </td> </tr> <td colspan = "2"> 6 Dicembre 2005 Stefano Clemente 76
Esempio 8: Guest. Book. Login. jsp <input type = "submit" value = "Submit" /> </td> </tr> </table> </form> <% // continue scriptlet } // end if else { guest. Data. add. Guest( guest ); %> <%-- end scriptlet to insert jsp: forward action --%> <%-- forward to display guest book contents --%> <jsp: forward page = "guest. Book. View. jsp" /> <% // continue scriptlet } // end else %> <%-- end scriptlet --%> </body> </html> 6 Dicembre 2005 Stefano Clemente 77
Esempio 8: Guest. Book. View. jsp <? xml version = "1. 0"? > <!DOCTYPE html PUBLIC "-//W 3 C//DTD XHTML 1. 0 Strict//EN" "http: //www. w 3. org/TR/xhtml 1/DTD/xhtml 1 -strict. dtd"> DIRETTIVE <!-- Fig. 10. 23: guest. Book. View. jsp --> <%-- page settings --%> <%@ page error. Page = "guest. Book. Error. Page. jsp" %> <%@ page import = "java. util. *" %> <%@ page import = "com. deitel. advjhtp 1. jsp. beans. *" %> <%-- Guest. Data. Bean to obtain guest list --%> <jsp: use. Bean id = "guest. Data" scope = "request" class = "com. deitel. advjhtp 1. jsp. beans. Guest. Data. Bean" /> <html xmlns = "http: //www. w 3. org/1999/xhtml"> <head> <title>Guest List</title> 6 Dicembre 2005 Stefano Clemente 78
Esempio 8: Guest. Book. View. jsp <style type = "text/css"> body { font-family: tahoma, helvetica, arial, sans-serif; } table, tr, td, th { text-align: center; font-size: . 9 em; border: 3 px groove; padding: 5 px; background-color: #dddddd; } </style> </head> <body> <p style = "font-size: 2 em; ">Guest List</p> <table> <thead> <tr> 6 Dicembre 2005 Stefano Clemente 79
Esempio 8: Guest. Book. View. jsp <th style = "width: 100 px; ">Last name</th> <th style = "width: 100 px; ">First name</th> <th style = "width: 200 px; ">Email</th> </tr> </thead> <tbody> <% // start scriptlet List guest. List = guest. Data. get. Guest. List(); Iterator guest. List. Iterator = guest. List. iterator(); Guest. Bean guest; while ( guest. List. Iterator. has. Next() ) { guest = ( Guest. Bean ) guest. List. Iterator. next(); %> <%-- end scriptlet; insert fixed template data --%> <tr> 6 Dicembre 2005 Stefano Clemente 80
Esempio 8: Guest. Book. View. jsp <td><%= guest. get. Last. Name() %></td> <td><%= guest. get. First. Name() %></td> <a href = "mailto: <%= guest. get. Email() %>"> </td> </tr> <%= guest. get. Email() %></a> <% // continue scriptlet } // end while %> <%-- end scriptlet --%> </tbody> </table> </body> </html> 6 Dicembre 2005 Stefano Clemente 81
Esempio 8: Guest. Book. Error. Page. jsp <? xml version = "1. 0"? > <!DOCTYPE html PUBLIC "-//W 3 C//DTD XHTML 1. 0 Strict//EN" "http: //www. w 3. org/TR/xhtml 1/DTD/xhtml 1 strict. dtd"> <!-- Fig. 10. 24: guest. Book. Error. Page. jsp --> <%-- page settings --%> <%@ page is. Error. Page = "true" %> <%@ page import = "java. util. *" %> <%@ page import = "java. sql. *" %> DIRETTIVE <html xmlns = "http: //www. w 3. org/1999/xhtml"> <head> <title>Error!</title> 6 Dicembre 2005 Stefano Clemente 82
Esempio 8: Guest. Book. Error. Page. jsp <style type = "text/css">. big. Red { font-size: 2 em; color: red; font-weight: bold; } </style> </head> <body> <p class = "big. Red"> <% // scriptlet to determine exception type // and output beginning of error message if ( exception instanceof SQLException ) { 6 Dicembre 2005 Stefano Clemente 83
Esempio 8: Guest. Book. Error. Page. jsp %> An SQLException <% } else if ( exception instanceof Class. Not. Found. Exception ) { %> A Class. Not. Found. Exception <% } else { %> An exception 6 Dicembre 2005 Stefano Clemente 84
Esempio 8: Guest. Book. Error. Page. jsp %> <%-- end scriptlet to insert fixed template data -- <%-- continue error message output --%> occurred while interacting with the guestbook database. <% } %> </p> <p class = "big. Red"> The error message was: <%= exception. get. Message() %> </p> <p class = "big. Red">Please try again later</p> </body> </html> 6 Dicembre 2005 Stefano Clemente 85
Esempio 8: File JSP 6 Dicembre 2005 Stefano Clemente 86
Esempio 8: File Java. Bean (Plug-in) 6 Dicembre 2005 Stefano Clemente 87
Esempio 8: le direttive per la gestione degli errori • La direttiva <%@ page error. Page = "guest. Book. Error. Page. jsp" %> è una direttiva di pagina che specifica a quale pagina inoltrare la richiesta in caso di errore • La direttiva <%@ page is. Error. Page = "true" %> è una direttiva di pagina • L’attributo is. Error. Page, is. Error. Page se settato a true, true rende la JSP una pagina di errore • L’effetto è di abilitare la JSP all’accesso all’oggetto implicito exception che contiene le informazioni sull’errore verificatosi 6 Dicembre 2005 Stefano Clemente 88
Direttive • Sono messaggi al JSP-container che permettono al programmatore di − specificare delle impostazioni per le pagine (es. pagina di errore) − includere il contenuto di altre risorse − specificare delle librerie di tag personalizzati da usare nelle JSP • Sono elaborate nel momento della traduzione, quindi prima che la JSP accetti qualsiasi richiesta • Sono delimitate da <%@ e da %> • Sono di tre tipi − − − page include taglib 6 Dicembre 2005 Stefano Clemente 89
La direttiva page • Specifica delle impostazioni globali della JSP all’interno del JSP-container • Possono esistere più direttive page purchè ve ne sia solo una per ogni attributo − l’unica eccezione è l’attributo import che permette alla JSP di importare i package necessari per la sua esecuzione 6 Dicembre 2005 Stefano Clemente 90
La direttiva page 6 Dicembre 2005 Stefano Clemente 91
La direttiva include • Include il contenuto di un’altra risorsa, ma solo quando la JSP viene tradotta (a differenza dell’azione <jsp: include>) : include> • L’unico attributo è file e specifica l’URL della pagina da includere • L’esempio seguente riscrive l’Esempio 3 sostituendo l’azione <jsp: include> con la direttiva include 6 Dicembre 2005 Stefano Clemente 92
Esempio 8: include. Directive. jsp <? xml version = "1. 0"? > <!DOCTYPE html PUBLIC "-//W 3 C//DTD XHTML 1. 0 Strict//EN" "http: //www. w 3. org/TR/xhtml 1/DTD/xhtml 1 -strict. dtd"> <!-- Fig. 10. 28: include. Directive. jsp --> <html xmlns = "http: //www. w 3. org/1999/xhtml"> <head> <title>Using the include directive</title> <style type = "text/css"> body { font-family: tahoma, helvetica, arial, sans-serif; } table, tr, td { font-size: . 9 em; border: 3 px groove; padding: 5 px; background-color: #dddddd; } </style> </head> <body> <table> <tr> <td style = "width: 160 px; text-align: center"> 6 Dicembre 2005 Stefano Clemente 93
Esempio 9: include. Directive. jsp < img src width alt = </td > </td> = "images /logotiny. png" "images/ logotiny. png" = "140" height = "93" " Deitel & Associates, Inc. Logo" /> <td> <%-- include banner. html in this JSP --%> <%@ include file = " banner. html" %> </td> </tr> <tr> <td : 160 px"> <td style = "width: <%-- include toc. html in this JSP --%> <%@ include file = " toc. html" %> </td> <td : top"> <td style = "vertical-align: <%-- include clock 2. jsp in this JSP --%> <%@ include file = "clock 2. jsp" %> </td> </tr> </table> </body> </html> 6 Dicembre 2005 Stefano Clemente 94
Custom Tag Libraries • Permettono di definire dei tag personalizzati attraverso i quali creare contenuti dinamici • La funzionalità è definita nelle classi Java che implementano l’interfaccia Tag javax. servlet. jsp. tagext in genere estendendo la classe Tag. Support o Body. Tag. Support • Attraverso questo meccanismo un programmatore Java può creare funzionalità complesse che possono essere facilmente utilizzate da disegnatori di pagine senza alcuna conoscenza di Java − a differenza dei Java. Bean, che pur permettendo di realizzare funzionalità complesse, richiedono agli utilizzatori una certa conoscenza di Java 6 Dicembre 2005 Stefano Clemente 95
Direttiva taglib • È la direttiva per l’uso dei custom tag • Ha due attributi − uri – specifica l’URI assoluta o relativa del descrittore della libreria di tag − prefix – specifica il prefisso che serve per distinguere i tag personalizzati dagli altri • non è consentito l’uso dei prefissi jsp, jspx, jspx java, javax, javax servlet, servlet sun e sunw 6 Dicembre 2005 Stefano Clemente 96
Implementazione dei custom tag • Definire 1. una classe per ogni custom tag che implementa la funzionalità del tag 2. un descrittore della libreria tag che fornisca al JSP container le informazioni relative alla libreria tag e ai suoi custom tag 3. una JSP che usa il custom tag 6 Dicembre 2005 Stefano Clemente 97
Esempio 10 6 Dicembre 2005 Stefano Clemente 98
Esempio 10 – Passo 1 implementazione custom tag: Welcome. Tag. Handler. java // Fig. 10. 31: Welcome. Tag. Handler. java // Custom tag handler that handles a simple tag. package com. deitel. advjhtp 1. jsp. taglibrary; // Java core packages import java. io. *; // Java extension packages import javax. servlet. jsp. *; import javax. servlet. jsp. tagext. *; public class Welcome. Tag. Handler extends Tag. Support { // Method called to begin tag processing public int do. Start. Tag() throws Jsp. Exception { // attempt tag processing try { // obtain Jsp. Writer to output content Jsp. Writer out = page. Context. get. Out (); } // output content out. print ( "Welcome to JSP Tag Libraries!" out. print( Libraries!" ); // rethrow IOException to JSP container as Jsp. Exception catch( IOException io. Exception ) { throw new Jsp. Exception( io. Exception. get. Message () ); } } } return SKIP_BODY; 6 Dicembre 2005 // ignore the tag's body Stefano Clemente 99
Esempio 10 – Passo 2 implementazione custom tag: advjhtp 1 -taglib. tld <? xml version = "1. 0"? > <!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc. //DTD JSP Tag Library 1. 1//EN" "http: //java. sun. com/j 2 ee/ dtds/web-jsptaglibrary_1_1. dtd"> <!-<!-- a tag library descriptor --> <taglib> <tlibversion >1. 0</tlibversion> > <tlibversion>1. 0</ <jspversion >1. 1</jspversion> > <jspversion>1. 1</ <shortname >advjhtp 1</shortname> > <shortname>advjhtp 1</ <info > <info> A simple tab library for the examples </info > </info> <!-<!-- A simple tag that outputs content --> <tag> <name>welcome</name> <tagclass> com. deitel. advjhtp 1. jsp. taglibrary. Welcome. Tag. Handler </tagclass > </tagclass> <bodycontent >empty</ bodycontent> > <bodycontent> empty</bodycontent <info > <info> Inserts content welcoming user to tag libraries </info > </info> </tag> ……… spazio per altri tag ……… </taglib > </taglib> 6 Dicembre 2005 Stefano Clemente 100
Esempio 10: custom. Tag. Welcome. jsp <? xml version = "1. 0"? > <!DOCTYPE HTML PUBLIC "-//W 3 C//DTD HTML 4. 0 Transitional//EN"> <!-- Fig. 10. 30: custom. Tag. Welcome. jsp --> <!-- JSP that uses a custom tag to output content. --> <!-- taglib directive --> <%@ taglib uri = "advjhtp 1 -taglib. tld" prefix = "advjhtp 1" %> <html xmlns = "http: //www. w 3. org/1999/xhtml"> <head> <title>Simple Custom Tag Example</title> </head> <body> <p>The following text demonstrates a custom tag: </p> <h 1> <advjhtp 1: welcome /> </h 1> </body> </html> 6 Dicembre 2005 Stefano Clemente 101
Esempio 10: i file. jsp e. tld 6 Dicembre 2005 Stefano Clemente 102
Esempio 10: la classe 6 Dicembre 2005 Stefano Clemente 103
Esempio 11: custom tag con attributi 6 Dicembre 2005 Stefano Clemente 104
Esempio 11: custom tag con attributi 6 Dicembre 2005 Stefano Clemente 105
Esempio 11: custom. Tag. Attribute. jsp <? xml version = "1. 0"? > <!DOCTYPE HTML PUBLIC "-//W 3 C//DTD HTML 4. 0 Transitional//EN"> <!---> <!-- Fig. 10. x: custom. Tag. Attribute. jsp --> <!-<!-- JSP that uses a custom tag to output content. --> <%-- taglib directive --%> <%@ taglib uri = "advjhtp 1 -taglib. tld" prefix = "advjhtp 1" %> <html xmlns = "http: //www. w 3. org/1999/ xhtml"> <head> <title >Specifying Custom Tag Attributes</ title> > <title> Attributes</title </head> <body> <p>Demonstrating an attribute with a string value</p> <h 1> <advjhtp 1: welcome 2 first. Name = "Paul " /> "Paul" </h 1> <p>Demonstrating an attribute with an expression value</p> <h 1> <%-- scriptlet to obtain "name" request parameter --%> <% String name = request. get. Parameter ( "name" ); %> <advjhtp 1: welcome 2 first. Name = "<%= name %>" /> </h 1> </body> </html> 6 Dicembre 2005 Stefano Clemente 106
Esempio 11: Welcome 2 Tag. Handler. java // Fig. 10. 34: Welcome 2 Tag. Handler. java // Custom tag handler that handles a simple tag. package com. deitel. advjhtp 1. jsp. taglibrary; // Java core packages import java. io. *; // Java extension packages import javax. servlet. jsp. *; import javax. servlet. jsp. tagext. *; public class Welcome 2 Tag. Handler extends Tag. Support { private String first. Name = ""; // Method called to begin tag processing public int do. Start. Tag() throws Jsp. Exception { // attempt tag processing try { // obtain Jsp. Writer to output content 6 Dicembre 2005 Stefano Clemente 107
Esempio 11: Welcome 2 Tag. Handler. java Jsp. Writer out = page. Context. get. Out(); } // output content out. print( "Hello " + first. Name + ", Welcome to JSP Tag Libraries!" ); // rethrow IOException to JSP container as Jsp. Exception catch( IOException io. Exception ) { throw new Jsp. Exception( io. Exception. get. Message() ); } } } return SKIP_BODY; // ignore the tag's body // set first. Name attribute to the users first name public void set. First. Name( String username ) { first. Name = username; } 6 Dicembre 2005 Stefano Clemente 108
Esempio 11: advjhtp 1 -taglib. tld ……………… <!-- A tag with an attribute --> <tag> <name>welcome 2</name> <tagclass> com. deitel. advjhtp 1. jsp. taglibrary. Welcome 2 Tag. Handler </tagclass> <bodycontent>empty</bodycontent> <info> Inserts content welcoming user to tag libraries. Uses attribute "name" to insert the user's name. </info> <attribute> <name>first. Name</name> <required>true</required> <rtexprvalue>true</rtexprvalue> </attribute> </tag> ……………… 6 Dicembre 2005 Stefano Clemente 109
Esempio 11: advjhtp 1 -taglib. tld • L’elemento attribute specifica le caratteristiche degli attributi del tag − name indica il nome dell’attributo − required indica se l’attributo è richiesto (true) true o opzionale (false) false − rtexprvalue indica se il valore può provenire da un’espressione JSP valutata a run-time (true) true o se deve essere passato come valore letterale (false) false 6 Dicembre 2005 Stefano Clemente 110
Esempio 11: i file. jsp e. tld 6 Dicembre 2005 Stefano Clemente 111
Esempio 11: la classe 6 Dicembre 2005 Stefano Clemente 112
Esempio 12: interazione con il body 6 Dicembre 2005 Stefano Clemente 113
Esempio 12: custom. Tag. Body. jsp <? xml version = "1. 0"? > <!DOCTYPE HTML PUBLIC "-//W 3 C//DTD HTML 4. 0 Transitional//EN"> <!-- custom. Tag. Body. jsp --> <%-- taglib directive --%> <%@ taglib uri = "advjhtp 1 -taglib. tld" prefix = "advjhtp 1" %> <html xmlns = "http: //www. w 3. org/1999/xhtml"> <head> <title>Guest List</title> <style type = "text/css"> body { font-family: tahoma, helvetica, arial, sans-serif } table, tr, td, th { text-align: center; font-size: . 9 em; border: 3 px groove; padding: 5 px; background-color: #dddddd } </style> </head> 6 Dicembre 2005 Stefano Clemente 114
Esempio 12: custom. Tag. Body. jsp <body> <p style = "font-size: 2 em">Guest List</p> <table> <thead> <th style = "width: 100 px">Last name</th> <th style = "width: 100 px">First name</th> <th style = "width: 200 px">Email</th> </thead> <%-- guestlist custom tag --%> <advjhtp 1: guestlist> <tr> <td><%= last. Name %></td> <td><%= first. Name %></td> <a href = "mailto: <%= email %>"> <%= email %></a> </td> </tr> </advjhtp 1: guestlist> </table> </body> </html> 6 Dicembre 2005 Stefano Clemente 115
Esempio 12: custom. Tag. Body. jsp • Si osservi che − le espressioni JSP dell’elemento guestlist usano variabili non definite nella JSP • queste variabili sono definite dal gestore del tag quando il tag è utilizzato • le variabili sono definite nel Page. Context cosicché possano essere usate nella pagina − sebbene non ci siano ripetizioni definite nella JSP, la tabella contiene tutte le righe del DB come se queste fossero frutto di una ripetizione • infatti, il gestore del tag è definito in modo da iterare su tutte le righe del DB 6 Dicembre 2005 Stefano Clemente 116
Esempio 12: Guest. Book. Tag. java • Il gestore del tag istanzia Guest. Data. Bean per l’accesso al DB • Guest. Book. Tag estende la classe Body. Tag. Support che contiene i metodi dell’interfaccia Body. Tag − do. Init. Body • richiamato una sola volta dopo do. Start. Tag e prima di do. After. Body • se do. Start. Tag restituisce Tag. SKIP_BODY, Tag. SKIP_BODY non viene richiamato − do. After. Body • richiamato tutte le volte che occorrono per elaborare il corpo del tag, ogni volta che viene restituito un Tag. EVAL_BODY_TAG • dopo un Tag. SKIP_BODY non viene più richiamato 6 Dicembre 2005 Stefano Clemente 117
Esempio 12: Guest. Book. Tag. java // Fig. 10. 37: Guest. Book. Tag. java // Custom tag handler that reads information from the guestbook // database and makes that data available in a JSP. package com. deitel. advjhtp 1. jsp. taglibrary; // Java core packages import java. io. *; import java. util. *; // Java extension packages import javax. servlet. jsp. *; import javax. servlet. jsp. tagext. *; // Deitel packages import com. deitel. advjhtp 1. jsp. beans. *; public class Guest. Book. Tag extends Body. Tag. Support { private String first. Name; private String last. Name; private String email; private Guest. Data. Bean guest. Data; private Guest. Bean guest; 6 Dicembre 2005 Stefano Clemente 118
Esempio 12: Guest. Book. Tag. java private Iterator iterator; // Method called to begin tag processing public int do. Start. Tag() throws Jsp. Exception { // attempt tag processing try { guest. Data = new Guest. Data. Bean(); List list = guest. Data. get. Guest. List(); iterator = list. iterator(); if ( iterator. has. Next() ) { process. Next. Guest(); return EVAL_BODY_TAG; } } else return SKIP_BODY; // continue body processing // terminate body processing // if any exceptions occur, do not continue processing // tag's body catch ( Exception exception ) { 6 Dicembre 2005 Stefano Clemente 119
Esempio 12: Guest. Book. Tag. java } } exception. print. Stack. Trace(); return SKIP_BODY; // ignore the tag's body // process body and determine if body processing // should continue public int do. After. Body() { // attempt to output body data try { body. Content. write. Out( get. Previous. Out() ); } // if exception occurs, terminate body processing catch ( IOException io. Exception ) { io. Exception. print. Stack. Trace(); return SKIP_BODY; // terminate body processing } body. Content. clear. Body(); if ( iterator. has. Next() ) { 6 Dicembre 2005 Stefano Clemente 120
Esempio 12: Guest. Book. Tag. java process. Next. Guest(); return EVAL_BODY_TAG; } } else return SKIP_BODY; // continue body processing // terminate body processing // obtains the next Guest. Bean and extracts its data private void process. Next. Guest() { // get next guest = ( Guest. Bean ) iterator. next(); page. Context. set. Attribute( "first. Name", guest. get. First. Name() ); page. Context. set. Attribute( "last. Name", guest. get. Last. Name() ); } } page. Context. set. Attribute( "email", guest. get. Email() ); 6 Dicembre 2005 Stefano Clemente 121
Esempio 12: Guest. Book. Tag. Extra. Info. java • process. Next. Guest usa Pages. Context. set. Attribute per specificare il nome e il valore di ogni attributo • Il JSP container si fa carico di creare le variabili utilizzate nella JSP − non può creare le variabili nel Page. Context a meno che non conosca il nome e il tipo delle variabili • Per specificare queste informazioni occorre definire una classe con lo stesso nome del gestore del tag e con Extra. Info alla fine − Guest. Book. Tag. Extra. Info. class 6 Dicembre 2005 Stefano Clemente 122
Esempio 12: Guest. Book. Tag. Extra. Info. java • Extra. Info estende la classe Tag. Extra. Info del package javax. servlet. jsp. tagext • Il container usa le informazioni specificate da una sottoclasse di Tag. Extra. Info per determinare le variabili da creare • Per specificare le variabili bisogna definire il metodo get. Variable. Info in override al metodo ereditato dalla classe − questo metodo restituisce un array di oggetti Variable. Info che il container utilizzerà per creare le nuove variabili nel Page. Context o per autorizzare il custom tag a utilizzarne di esistenti 6 Dicembre 2005 Stefano Clemente 123
Esempio 12: Guest. Book. Tag. Extra. Info. java • Il costruttore Variable. Info accetta quattro argomenti − il nome della variabile – String − il nome della classe alla quale appartiene la variabile (tipo di dati) – String − boolean • true – il container dovrà creare la variabile • false – altrimenti − portata della variabile nella JSP – intero static • NESTED – la variabile può essere usata solo nel corpo del custom tag • AT_BEGIN – la variabile può essere usata ovunque nella JSP dopo a partire dal tag di apertura del custom tag • AT_END – la variabile può essere usata ovunque nella JSP dopo a partire dal tag di chiusura del custom tag 6 Dicembre 2005 Stefano Clemente 124
Esempio 12: Guest. Book. Tag. Extra. Info. java // Fig. 10. 38: Guest. Book. Tag. Extra. Info. java // Class that defines the variable names and types created by // custom tag handler Guest. Book. Tag. package com. deitel. advjhtp 1. jsp. taglibrary; // Java core packages import javax. servlet. jsp. tagext. *; public class Guest. Book. Tag. Extra. Info extends Tag. Extra. Info { // method that returns information about the variables // Guest. Book. Tag creates for use in a JSP public Variable. Info [] get. Variable. Info( Tag. Data tag. Data ) { Variable. Info first. Name = new Variable. Info( "first. Name", "String", true, Variable. Info. NESTED ); Variable. Info last. Name = new Variable. Info( "last. Name", "String", true, Variable. Info. NESTED ); Variable. Info email = new Variable. Info( "email", "String", true, Variable. Info. NESTED ); Variable. Info varable. Info [] = { first. Name, last. Name, email }; } } return varable. Info; 6 Dicembre 2005 Stefano Clemente 125
Esempio 12: advjhtp 1 -taglib. tld ……………… <!-- A tag that iterates over an Array. List of Guest. Bean --> <!-- objects, so they can be output in a JSP --> <tag> <name>guestlist</name> <tagclass> com. deitel. advjhtp 1. jsp. taglibrary. Guest. Book. Tag </tagclass> <teiclass> com. deitel. advjhtp 1. jsp. taglibrary. Guest. Book. Tag. Extra. Info </teiclass> <bodycontent>JSP</bodycontent> <info> Iterates over a list of Guest. Bean objects </info> </tag> ……………… 6 Dicembre 2005 Stefano Clemente 126
Esempio 12: i file. jsp e. tld 6 Dicembre 2005 Stefano Clemente 127
Esempio 11: la classe 6 Dicembre 2005 Stefano Clemente 128
Esempio 12: i Java. Beans 6 Dicembre 2005 Stefano Clemente 129
- Java server pages tutorial
- Java server pages life cycle
- Java server pages
- Java server pages
- Java server pages
- Printed pages vs web pages
- Uso responsabile delle tecnologie
- Tesina sul progresso
- Cosa significa tic
- Ente per le nuove tecnologie
- Ente per le nuove tecnologie
- Mosaico tecnologie
- Sistema alimentare sostenibilità management e tecnologie
- Nuove tecnologie fotovoltaico
- Java jsp
- Java jsp
- Nnn tutorial
- Jsp v
- Java ee jsp
- Active server pages paradigma
- Condizioni sufficienti trapezio isoscele
- Jerzy duda gracz babie lato
- Typ urody lato
- Una scatola cubica di lato 25 cm
- Jesienne wiersze dla dzieci
- Lato b marta menegatti
- Criterio del tir
- Quadrato dei lombi
- Lato wiersze dla dzieci
- Carmen freitas
- Organi lato destro
- Apotema pentagono
- Jsp technology
- Exemple oral brevet pdf
- Jsp bus
- The anatomy of a jsp page
- Climatic injuries
- Climatic injury
- Jsp engine
- Jsp engine
- Anatomy of a jsp page
- Jsp engine
- Mvc architecture in jsp
- Actioncart
- Servlet jdbc
- Jsp page directive
- Jsp include html
- Jsp 34
- Introduction to jsp
- Jsp standard action tags
- Exercice jsp
- Jsp overview
- Korean.jsp?include= site:com
- Propfind 메소드 취약점
- What are jstl tags
- Jsp database access
- Jsp architecture diagram
- Etiquetas jsp
- Define jsp
- Scriplets
- Jsp 1
- Mineresepter.no/mineresepter/velkommen.jsp
- Etiquetas jsp
- Thymeleaf
- Payroll card
- Custom tags in jsp
- Javascript framework
- Jsp 539
- Commentaire jsp
- Jsp 구구단
- Comentarios en jsp
- Java swing form example
- Import java.util.*
- Import javax.swing.*
- Import java.util.* use
- Import java.io.* import java.util.*
- Gcd java
- Import java util random
- Java import java.io.*
- Import java.util
- Java import java.io.*
- Perbedaan antara java swing dan awt adalah
- Import java.awt.event.*;
- Language
- Ejb in javatpoint
- Java irc bot
- Java irc
- Android udp client
- Java.rmi.server.codebase
- Lập trình socket giao tiếp tcp client/server java
- Knock knock server java
- Stefano stoppani
- Stefano lupi
- Stefano profumo
- Stefano pantaleoni
- Stefano pigliapoco
- Stefano federici
- Legramanti stefano
- Stefano scarcella prandstraller
- Stefano palminteri
- Stefano miceli sopo
- Stefano tessaro
- Stefano berloffa stella maris
- Stefano bigolaro
- Stefano cassamagnaghi
- Tamara stefano
- Stefano panebianco
- Stefano bertoldo
- Stefano matti agr
- Stefano saviola
- Stefano vignudelli
- Santo stefano harding
- Stefano mignani
- Stefano danese
- Stefano monti iaea
- Stefano daldosso
- Simona di stefano psicologa
- Stefano sanvito
- Stefano grazioli
- Stefano dei ovi
- Stefano cancarini
- Stefano ronchi polimi
- Stefano lupi sapienza
- Stefano tonelato
- Stefano lagomarsino
- Stefano soatto ucla
- Stefano olmeti
- Stefano balietti
- Stefano balietti
- Secuencia narrativa de stefano