La presentazione è in caricamento. Aspetta per favore

La presentazione è in caricamento. Aspetta per favore

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

Presentazioni simili


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

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

2 6 Dicembre 2005Stefano Clemente2 Riferimenti bibliografici H. M. Deitel, P. J. Deitel, T. R. Nieto Internet & World Wide Web – How To Program (Second Edition) ed. Prentice Hall 2002 Capitolo 31 (sul CD allegato al libro) http://java.sun.com/developer/onlineTra ining/JSPIntro/contents.html http://jakarta.apache.org

3 6 Dicembre 2005Stefano Clemente3 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

4 6 Dicembre 2005Stefano Clemente4 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 JavaBeans; 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 ricaricamento 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

5 6 Dicembre 2005Stefano Clemente5 Introduzione Il contenuto dinamico può essere inviato in vari formati − Le JSP possono essere richieste da vari client Browser Cellulari PDA Applicazioni B2B che fanno uso di XML Consigliate per applicazioni client/server a n- livelli 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 6 Dicembre 2005Stefano Clemente6 Introduzione Le JavaServer Pages (JSP) sono un’estensione della tecnologia Servlet Sono progettate per semplificare l’invio di contenuti dinamici Package addizionali javax.servlet.jsp − Package javax.servlet.jsp Contiene la maggior parte delle classi e dei metodi di JSP javax.servlet.jsp.tagtest − Package javax.servlet.jsp.tagtest Contiene le classi e i metodi per i custom tag

7 6 Dicembre 2005Stefano Clemente7 Componenti di JSP DirettiveDirettive − Sono messaggi al JSP-Container che permettono di specificare impostazioni della pagina includere contenuti da altre risorse specificare tag definiti dall’utente da utilizzare AzioniAzioni − 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 eLEmenTS)Scriptlets (SCRIPTing eLEmenTS) − permettono di inserire codice Java nelle JSP (e altre componenti dell’applicazione web) per eseguire la richiesta del client Librerie di TagLibrerie di Tag − sono parte del meccanismi di estensione dei tag che permette al programmatore di creare dei propri tag

8 6 Dicembre 2005Stefano Clemente8 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 − jspInit − jspService − jspDestroy

9 6 Dicembre 2005Stefano Clemente9 Esempio 1

10 6 Dicembre 2005Stefano Clemente10 Esempio 1: clock.jsp <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <head> A Simple JSP Example A Simple JSP Example.big { font-family: helvetica, arial, sans-serif;.big { font-family: helvetica, arial, sans-serif; font-weight: bold; font-size: 2em; } </head>

11 6 Dicembre 2005Stefano Clemente11 Esempio 1: clock.jsp <body> Simple JSP Example Simple JSP Example </td> </body></html> Espressione JSP

12 6 Dicembre 2005Stefano Clemente12 Esempio 1

13 6 Dicembre 2005Stefano Clemente13 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

14 6 Dicembre 2005Stefano Clemente14 Oggetti Impliciti

15 6 Dicembre 2005Stefano Clemente15 Scripting Permette di inserire del codice Java nelle pagine JSP aggiungendo così contenuti dinamici Componenti − Scriptlets (Script Elements) Delimitati da Blocchi di codice Java − Commenti //Commenti Scriptlet delimitati da / e / Commenti JSP delimitati da -->Commenti XHTML delimitati da − Espressioni Delimitate da StringRisultati convertiti in oggetti String

16 6 Dicembre 2005Stefano Clemente16 Scripting … Componenti − Dichiarazioni Delimitate da 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 − <\% − %/> − \’ − \” − \\

17 6 Dicembre 2005Stefano Clemente17 Esempio 2

18 6 Dicembre 2005Stefano Clemente18 Esempio 1: welcome.jsp <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> Processing "get" requests with data Processing "get" requests with data <% // begin scriptlet <% // begin scriptlet String name = request.getParameter( "firstName" ); String name = request.getParameter( "firstName" ); if ( name != null ) { if ( name != null ) { %> %> Hello, Hello,

19 6 Dicembre 2005Stefano Clemente19 Esempio 1: welcome.jsp Welcome to JavaServer Pages! Welcome to JavaServer Pages! <% // continue scriptlet <% // continue scriptlet } // end if } // end if else { else { %> %> Type your first name and press Submit Type your first name and press Submit <% // continue scriptlet <% // continue scriptlet } // end else } // end else %> %>

20 6 Dicembre 2005Stefano Clemente20 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 JavaBeans Sono elaborate dal JSP Container al momento della richiesta della risorsa Sono delimitate dai tag e − Nel caso in cui non vi fosse niente da includere tra il tag di inizio e quello di chiusura si può usare

21 6 Dicembre 2005Stefano Clemente21 Azioni Standard

22 6 Dicembre 2005Stefano Clemente22 <jsp:include> JSP fornisce due tipi di meccanismi di inclusione − Azione 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 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

23 6 Dicembre 2005Stefano Clemente23 <jsp:include> Attributi di − 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 trueIn JSP 1.1 questo attributo deve valere true

24 6 Dicembre 2005Stefano Clemente24 Esempio 3 Viene mostrato l’uso dell’azione attraverso l’inclusione di contenuti sia statici sia dinamici include.jspIl documento include.jsp include tre altri documenti − banner.html − toc.html − clock2.jsp include.jspIn particolare include.jsp è una tabella che: banner.html − nella parte alta mostra banner.html toc.html − a sinistra mostra toc.html clock2.jsp − a destra mostra clock2.jsp

25 6 Dicembre 2005Stefano Clemente25 Esempio 3

26 6 Dicembre 2005Stefano Clemente26 Esempio 3: banner.html Java(TM), C, C++, Visual Basic(R), Java(TM), C, C++, Visual Basic(R), Object Technology, and Internet and Object Technology, and Internet and World Wide Web Programming Training World Wide Web Programming Training On-Site Seminars Delivered Worldwide On-Site Seminars Delivered Worldwide deitel@deitel.com deitel@deitel.com 978.579.9911 978.579.9911 490B Boston Post Road, Suite 200, 490B Boston Post Road, Suite 200, Sudbury, MA 01776 Sudbury, MA 01776 </div>

27 6 Dicembre 2005Stefano Clemente27 Esempio 3: toc.html Publications/BookStore Publications/BookStore</a></p> What's New What's New</a></p> Downloads/Resources Downloads/Resources</a></p> FAQ (Frequently Asked Questions) FAQ (Frequently Asked Questions)</a></p> Who we are Who we are</a></p> Home Page Home Page</a></p> Send questions or comments about this site to Send questions or comments about this site to deitel@deitel.com deitel@deitel.com Copyright 1995-2002 by Deitel & Associates, Inc. Copyright 1995-2002 by Deitel & Associates, Inc. All Rights Reserved. All Rights Reserved.</p>

28 6 Dicembre 2005Stefano Clemente28 Esempio 3: clock2.jsp <table> <p class = "big" style = "color: cyan; font-size: 3em; <p class = "big" style = "color: cyan; font-size: 3em; font-weight: bold;"> font-weight: bold;"> </table>

29 6 Dicembre 2005Stefano Clemente29 Esempio 3: include.jsp <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> Using jsp:include Using jsp:include body { body { font-family: tahoma, helvetica, arial, sans- serif; font-family: tahoma, helvetica, arial, sans- serif; }

30 6 Dicembre 2005Stefano Clemente30 Esempio 3: include.jsp table, tr, td { table, tr, td { font-size:.9em; font-size:.9em; border: 3px groove; border: 3px groove; padding: 5px; padding: 5px; background-color: #dddddd; background-color: #dddddd; } <img src = "images/logotiny.png" <img src = "images/logotiny.png" width = "140" height = "93" width = "140" height = "93"

31 6 Dicembre 2005Stefano Clemente31 Esempio 3: include.jsp alt = "Deitel & Associates, Inc. Logo" /> alt = "Deitel & Associates, Inc. Logo" /> <jsp:include page = "banner.html" <jsp:include page = "banner.html" flush = "true" /> flush = "true" />

32 6 Dicembre 2005Stefano Clemente32 Esempio 3: include.jsp <jsp:include page = "clock2.jsp" <jsp:include page = "clock2.jsp" flush = "true" /> flush = "true" /> </html>

33 6 Dicembre 2005Stefano Clemente33 <jsp:forward> Permette di inoltrare una richiesta a un’altra risorsa La richiesta alla pagina JSP originaria contenente l’azione termina non appena viene inoltrata la richiesta page ha solo un attributo page che specifica l’URI della risorsa (all’interno della stessa applicazione)

34 6 Dicembre 2005Stefano Clemente34 Esempio 4

35 6 Dicembre 2005Stefano Clemente35 Esempio 4: forward1.jsp <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <head> Forward request to another JSP Forward request to another JSP </head><body> <% // begin scriptlet <% // begin scriptlet String name = request.getParameter( "firstName" ); String name = request.getParameter( "firstName" ); if ( name != null ) { if ( name != null ) { %> %> <jsp:param name = "date" <jsp:param name = "date" value = " " /> value = " " />

36 6 Dicembre 2005Stefano Clemente36 Esempio 4: forward1.jsp <% // continue scriptlet <% // continue scriptlet } // end if } // end if else { else { %> %> Type your first name and press Submit Type your first name and press Submit <% // continue scriptlet <% // continue scriptlet } // end else } // end else %> %> </body>

37 6 Dicembre 2005Stefano Clemente37 Esempio 4: forward2.jsp <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <head> Processing a forwarded request Processing a forwarded request.big {.big { font-family: tahoma, helvetica, arial, sans- serif; font-family: tahoma, helvetica, arial, sans- serif; font-weight: bold; font-weight: bold; font-size: 2em; font-size: 2em; } </head>

38 6 Dicembre 2005Stefano Clemente38 Esempio 4: forward2.jsp <body> Hello, Hello, Your request was received and forwarded at Your request was received and forwarded at </body></html>

39 6 Dicembre 2005Stefano Clemente39 <jsp:param> nome/valorePermette di specificare coppie di parametri nome/valore da passare alle azioni − − ha due attributi: − name − name che specifica il nome del parametro − value − value che specifica il valore del parametro Se specifica un parametro già esistente nella richiesta, il valore passato con essa ha precedenza su quello della richiesta

40 6 Dicembre 2005Stefano Clemente40 Esempio 5

41 6 Dicembre 2005Stefano Clemente41 Esempio 5: forward3.jsp <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <head> Forward request to another JSP Forward request to another JSP </head><body> <% // begin scriptlet <% // begin scriptlet String name = request.getParameter( "firstName" ); String name = request.getParameter( "firstName" ); if ( name != null ) { if ( name != null ) { %> %> <jsp:param name = "firstName" <jsp:param name = "firstName" value = "Pippo" /> value = "Pippo" /> <jsp:param name = "date" <jsp:param name = "date" value = " " /> value = " " />

42 6 Dicembre 2005Stefano Clemente42 Esempio 5: forward3.jsp <% // continue scriptlet <% // continue scriptlet } // end if } // end if else { else { %> %> Type your first name and press Submit Type your first name and press Submit <% // continue scriptlet <% // continue scriptlet } // end else } // end else %> %> </body>

43 6 Dicembre 2005Stefano Clemente43 Esempi 4 e 5: File

44 6 Dicembre 2005Stefano Clemente44 <jsp:plugin> embedPermette di aggiungere Applet o JavaBean a una pagina sotto forma di un oggetto specifico del browser o di un elemento XHTML embed − Applet = … (v. gruppo di lucidi TecnInt8.pdf) − JavaBean = 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”

45 6 Dicembre 2005Stefano Clemente45 <jsp:plugin> L’azione abilita il client al download e all’installazione del plug-in nel caso questo non lo avesse già

46 6 Dicembre 2005Stefano Clemente46 Esempio 6 Applet

47 6 Dicembre 2005Stefano Clemente47 Esempio 6: ShapesApplet.java // Fig. 10.x: ShapesApplet.java // Applet that demonstrates a Java2D GeneralPath. package advjhtp1.jsp.applet; // Java core packages import java.applet.*; import java.awt.event.*; import java.awt.*; import java.awt.geom.*; // Java extension packages import javax.swing.*; public class ShapesApplet extends JApplet { // initialize the applet // initialize the applet public void init() public void init() { // obtain color parameters from XHTML file // obtain color parameters from XHTML file

48 6 Dicembre 2005Stefano Clemente48 Esempio 6: ShapesApplet.java try { try { int red = Integer.parseInt( getParameter( "red" ) ); int red = Integer.parseInt( getParameter( "red" ) ); int green = Integer.parseInt( getParameter( "green" ) ); int green = Integer.parseInt( getParameter( "green" ) ); int blue = Integer.parseInt( getParameter( "blue" ) ); int blue = Integer.parseInt( getParameter( "blue" ) ); Color backgroundColor = new Color( red, green, blue ); Color backgroundColor = new Color( red, green, blue ); setBackground( backgroundColor ); setBackground( backgroundColor ); } // if there is an exception while processing the color // if there is an exception while processing the color // parameters, catch it and ignore it // parameters, catch it and ignore it catch ( Exception exception ) { catch ( Exception exception ) { // do nothing // do nothing }} public void paint( Graphics g ) public void paint( Graphics g ) {

49 6 Dicembre 2005Stefano Clemente49 Esempio 6: ShapesApplet.java // create arrays of x and y coordinates // create arrays of x and y coordinates int xPoints[] = int xPoints[] = { 55, 67, 109, 73, 83, 55, 27, 37, 1, 43 }; { 55, 67, 109, 73, 83, 55, 27, 37, 1, 43 }; int yPoints[] = int yPoints[] = { 0, 36, 36, 54, 96, 72, 96, 54, 36, 36 }; { 0, 36, 36, 54, 96, 72, 96, 54, 36, 36 }; // obtain reference to a Graphics2D object // obtain reference to a Graphics2D object Graphics2D g2d = ( Graphics2D ) g; Graphics2D g2d = ( Graphics2D ) g; // create a star from a series of points // create a star from a series of points GeneralPath star = new GeneralPath(); GeneralPath star = new GeneralPath(); // set the initial coordinate of the GeneralPath // set the initial coordinate of the GeneralPath star.moveTo( xPoints[ 0 ], yPoints[ 0 ] ); star.moveTo( xPoints[ 0 ], yPoints[ 0 ] ); // create the star--this does not draw the star // create the star--this does not draw the star for ( int k = 1; k < xPoints.length; k++ ) for ( int k = 1; k < xPoints.length; k++ ) star.lineTo( xPoints[ k ], yPoints[ k ] ); star.lineTo( xPoints[ k ], yPoints[ k ] );

50 6 Dicembre 2005Stefano Clemente50 Esempio 6: ShapesApplet.java // close the shape // close the shape star.closePath(); star.closePath(); // translate the origin to (200, 200) // translate the origin to (200, 200) g2d.translate( 200, 200 ); g2d.translate( 200, 200 ); // rotate around origin and draw stars in random colors // rotate around origin and draw stars in random colors for ( int j = 1; j <= 20; j++ ) { for ( int j = 1; j <= 20; j++ ) { g2d.rotate( Math.PI / 10.0 ); g2d.rotate( Math.PI / 10.0 ); g2d.setColor( g2d.setColor( new Color( ( int ) ( Math.random() * 256 ), new Color( ( int ) ( Math.random() * 256 ), ( int ) ( Math.random() * 256 ), ( int ) ( Math.random() * 256 ), ( int ) ( Math.random() * 256 ) ) ); ( int ) ( Math.random() * 256 ) ) ); g2d.fill( star ); // draw a filled star g2d.fill( star ); // draw a filled star } }}

51 6 Dicembre 2005Stefano Clemente51 Esempio 6: plugin.jsp <html> Using jsp:plugin to load an applet Using jsp:plugin to load an applet <jsp:plugin type = "applet" <jsp:plugin type = "applet" code = "com.deitel.advjhtp1.jsp.applet.ShapesApplet" code = "com.deitel.advjhtp1.jsp.applet.ShapesApplet" codebase = "/advjhtp1/jsp" codebase = "/advjhtp1/jsp" width = "400" width = "400" height = "400"> height = "400"> </html>

52 6 Dicembre 2005Stefano Clemente52 Esempio 6

53 6 Dicembre 2005Stefano Clemente53 Esempio 6: File JSP

54 6 Dicembre 2005Stefano Clemente54 Esempio 6: File Applet (Plug-in)

55 6 Dicembre 2005Stefano Clemente55 <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

56 6 Dicembre 2005Stefano Clemente56 <jsp:usebean> class beanName typeSe non vengono specificati gli attributi class e beanName, il JSP-container cerca di individuare un oggetto del tipo specificato con l’attributo type pagerequestsessionapplicationProprio come gli oggetti impliciti, gli oggetti specificati con hanno portate dei tipi page, request, session, application page − 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

57 6 Dicembre 2005Stefano Clemente57 Esempio 7

58 6 Dicembre 2005Stefano Clemente58 Esempio 7: Rotator.java( Bean) // Fig. 10.17: Rotator.java // A JavaBean that rotates advertisements. package com.deitel.advjhtp1.jsp.beans; public class Rotator { private String images[] = { "images/jhtp3.jpg", private String images[] = { "images/jhtp3.jpg", "images/xmlhtp1.jpg", "images/ebechtp1.jpg", "images/xmlhtp1.jpg", "images/ebechtp1.jpg", "images/iw3htp1.jpg", "images/cpphtp3.jpg"}; "images/iw3htp1.jpg", "images/cpphtp3.jpg"}; private String links[] = { private String links[] = { "http://www.amazon.com/exec/obidos/ASIN/0130125075/" + "http://www.amazon.com/exec/obidos/ASIN/0130125075/" + "deitelassociatin", "deitelassociatin", "http://www.amazon.com/exec/obidos/ASIN/0130284173/" + "http://www.amazon.com/exec/obidos/ASIN/0130284173/" + "deitelassociatin", "deitelassociatin", "http://www.amazon.com/exec/obidos/ASIN/013028419X/" + "http://www.amazon.com/exec/obidos/ASIN/013028419X/" + "deitelassociatin", "deitelassociatin", "http://www.amazon.com/exec/obidos/ASIN/0130161438/" + "http://www.amazon.com/exec/obidos/ASIN/0130161438/" + "deitelassociatin", "deitelassociatin", "http://www.amazon.com/exec/obidos/ASIN/0130895717/" + "http://www.amazon.com/exec/obidos/ASIN/0130895717/" + "deitelassociatin" }; "deitelassociatin" };

59 6 Dicembre 2005Stefano Clemente59 Esempio 7: Rotator.java( Bean) private int selectedIndex = 0; private int selectedIndex = 0; // returns image file name for current ad // returns image file name for current ad public String getImage() public String getImage() { return images[ selectedIndex ]; return images[ selectedIndex ]; } // returns the URL for ad's corresponding Web site // returns the URL for ad's corresponding Web site public String getLink() public String getLink() { return links[ selectedIndex ]; return links[ selectedIndex ]; } // update selectedIndex so next calls to getImage and // update selectedIndex so next calls to getImage and // getLink return a different advertisement // getLink return a different advertisement public void nextAd() public void nextAd() { selectedIndex = ( selectedIndex + 1 ) % images.length; selectedIndex = ( selectedIndex + 1 ) % images.length; }}

60 6 Dicembre 2005Stefano Clemente60 Esempio 7: adrotator.jsp <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <jsp:useBean id = "rotator" scope = "session" class = "com.deitel.advjhtp1.jsp.beans.Rotator" /> class = "com.deitel.advjhtp1.jsp.beans.Rotator" /> AdRotator Example AdRotator Example.big { font-family: helvetica, arial, sans- serif;.big { font-family: helvetica, arial, sans- serif; font-weight: bold; font-weight: bold; font-size: 2em; } font-size: 2em; }

61 6 Dicembre 2005Stefano Clemente61 Esempio 7: adrotator.jsp AdRotator Example AdRotator Example <a href = "<jsp:getProperty name = "rotator" <a href = "<jsp:getProperty name = "rotator" property = "link" />"> property = "link" />"> <img src = "<jsp:getProperty name = "rotator" <img src = "<jsp:getProperty name = "rotator" property = "image" />" alt = "advertisement" /> property = "image" />" alt = "advertisement" /> </html>

62 6 Dicembre 2005Stefano Clemente62 Esempio 7: adrotator1.jsp AdRotator Example AdRotator Example "> "> " " alt = "advertisement" /> alt = "advertisement" /> </html>

63 6 Dicembre 2005Stefano Clemente63 Esempio 7: File JSP

64 6 Dicembre 2005Stefano Clemente64 Esempio 7: File JavaBean (Plug-in)

65 6 Dicembre 2005Stefano Clemente65 <jsp:getProperty> Serve per ottenere valori dal bean Ha due attributi − name − name – il nome del bean − property − property – la proprietà da recuperare getXyzabcQuando il JSP-container incontra cerca di invocare getXyz dall’oggetto abc Equivale a scrivere l’espressione JSP

66 6 Dicembre 2005Stefano Clemente66 <jsp:setProperty> Serve per settare valori nel bean

67 6 Dicembre 2005Stefano Clemente67 Esempio 8 1 1 2 2

68 6 Dicembre 2005Stefano Clemente68 Esempio 8: GuestBean.java // Fig. 10.20: GuestBean.java // JavaBean to store data for a guest in the guestbook. package com.deitel.advjhtp1.jsp.beans; public class GuestBean { private String firstName, lastName, email; private String firstName, lastName, email; // set the guest's first name // set the guest's first name public void setFirstName( String name ) public void setFirstName( String name ) { firstName = name; firstName = name; } // get the guest's first name // get the guest's first name public String getFirstName() public String getFirstName() { return firstName; return firstName; } // set the guest's last name // set the guest's last name public void setLastName( String name ) public void setLastName( String name )

69 6 Dicembre 2005Stefano Clemente69 Esempio 8: GuestBean.java { lastName = name; lastName = name; } // get the guest's last name // get the guest's last name public String getLastName() public String getLastName() { return lastName; return lastName; } // set the guest's email address // set the guest's email address public void setEmail( String address ) public void setEmail( String address ) { email = address; email = address; } // get the guest's email address // get the guest's email address public String getEmail() public String getEmail() { return email; return email; }}

70 6 Dicembre 2005Stefano Clemente70 Esempio 8: GuestDataBean.java // GuestDataBean.java // Class GuestDataBean makes a database connection and supports // inserting and retrieving data from the database. package com.deitel.advjhtp1.jsp.beans; // Java core packages import java.io.*; import java.sql.*; import java.util.*; public class GuestDataBean { private Connection connection; private Connection connection; private PreparedStatement addRecord, getRecords; private PreparedStatement addRecord, getRecords; // construct TitlesBean object // construct TitlesBean object public GuestDataBean() throws Exception public GuestDataBean() throws Exception { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); String filename = "c:/web/advjhtp1/guestbook.mdb"; String filename = "c:/web/advjhtp1/guestbook.mdb"; String database = "jdbc:odbc:Driver={Microsoft Access Driver " String database = "jdbc:odbc:Driver={Microsoft Access Driver " + "(*.mdb)};DBQ="; + "(*.mdb)};DBQ="; database+= filename.trim() + ";DriverID=22;READONLY=true}"; database+= filename.trim() + ";DriverID=22;READONLY=true}";

71 6 Dicembre 2005Stefano Clemente71 Esempio 8: GuestDataBean.java connection = DriverManager.getConnection( database,"",""); connection = DriverManager.getConnection( database,"",""); getRecords = getRecords = connection.prepareStatement( connection.prepareStatement( "SELECT firstName, lastName, email FROM guests" "SELECT firstName, lastName, email FROM guests" ); ); addRecord = addRecord = connection.prepareStatement( connection.prepareStatement( "INSERT INTO guests ( " + "INSERT INTO guests ( " + "firstName, lastName, email ) " + "firstName, lastName, email ) " + "VALUES ( ?, ?, ? )" "VALUES ( ?, ?, ? )" ); ); } // return an ArrayList of GuestBeans // return an ArrayList of GuestBeans public List getGuestList() throws SQLException public List getGuestList() throws SQLException { List guestList = new ArrayList(); List guestList = new ArrayList(); // obtain list of titles // obtain list of titles

72 6 Dicembre 2005Stefano Clemente72 Esempio 8: GuestDataBean.java ResultSet results = getRecords.executeQuery(); ResultSet results = getRecords.executeQuery(); // get row data // get row data while ( results.next() ) { while ( results.next() ) { GuestBean guest = new GuestBean(); GuestBean guest = new GuestBean(); guest.setFirstName( results.getString( 1 ) ); guest.setFirstName( results.getString( 1 ) ); guest.setLastName( results.getString( 2 ) ); guest.setLastName( results.getString( 2 ) ); guest.setEmail( results.getString( 3 ) ); guest.setEmail( results.getString( 3 ) ); guestList.add( guest ); guestList.add( guest ); } return guestList; return guestList; } // insert a guest in guestbook database // insert a guest in guestbook database public void addGuest( GuestBean guest ) throws SQLException public void addGuest( GuestBean guest ) throws SQLException { addRecord.setString( 1, guest.getFirstName() ); addRecord.setString( 1, guest.getFirstName() ); addRecord.setString( 2, guest.getLastName() ); addRecord.setString( 2, guest.getLastName() );

73 6 Dicembre 2005Stefano Clemente73 Esempio 8: GuestDataBean.java addRecord.setString( 3, guest.getEmail() ); addRecord.setString( 3, guest.getEmail() ); addRecord.executeUpdate(); addRecord.executeUpdate(); } // close statements and terminate database connection // close statements and terminate database connection protected void finalize() protected void finalize() { // attempt to close database connection // attempt to close database connection try { try { getRecords.close(); getRecords.close(); addRecord.close(); addRecord.close(); connection.close(); connection.close(); } // process SQLException on close operation // process SQLException on close operation catch ( SQLException sqlException ) { catch ( SQLException sqlException ) { sqlException.printStackTrace(); sqlException.printStackTrace(); } }}

74 6 Dicembre 2005Stefano Clemente74 Esempio 8: GuestBookLogin.jsp <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <jsp:useBean id = "guest" scope = "page" class = "com.deitel.advjhtp1.jsp.beans.GuestBean" /> class = "com.deitel.advjhtp1.jsp.beans.GuestBean" /> <jsp:useBean id = "guestData" scope = "request" class = "com.deitel.advjhtp1.jsp.beans.GuestDataBean" /> class = "com.deitel.advjhtp1.jsp.beans.GuestDataBean" /> <head> Guest Book Login Guest Book Login body { body { font-family: tahoma, helvetica, arial, sans-serif; font-family: tahoma, helvetica, arial, sans-serif; } DIRETTIVADIRETTIVA

75 6 Dicembre 2005Stefano Clemente75 Esempio 8: GuestBookLogin.jsp table, tr, td { table, tr, td { font-size:.9em; font-size:.9em; border: 3px groove; border: 3px groove; padding: 5px; padding: 5px; background-color: #dddddd; background-color: #dddddd; } </head><body> <% // start scriptlet <% // start scriptlet if ( guest.getFirstName() == null || if ( guest.getFirstName() == null || guest.getLastName() == null || guest.getLastName() == null || guest.getEmail() == null ) { guest.getEmail() == null ) { %> %> Enter your first name, last name and email Enter your first name, last name and email address to register in our guest book. address to register in our guest book.

76 6 Dicembre 2005Stefano Clemente76 Esempio 8: GuestBookLogin.jsp First name First name Last name Last name Email Email

77 6 Dicembre 2005Stefano Clemente77 Esempio 8: GuestBookLogin.jsp <input type = "submit" <input type = "submit" value = "Submit" /> value = "Submit" /> <% // continue scriptlet <% // continue scriptlet } // end if } // end if else { else { guestData.addGuest( guest ); guestData.addGuest( guest ); %> %> <% // continue scriptlet <% // continue scriptlet } // end else } // end else %> %> </body></html>

78 6 Dicembre 2005Stefano Clemente78 Esempio 8: GuestBookView.jsp <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <jsp:useBean id = "guestData" scope = "request" class = "com.deitel.advjhtp1.jsp.beans.GuestDataBean" /> class = "com.deitel.advjhtp1.jsp.beans.GuestDataBean" /> Guest List Guest List DIRETTIVEDIRETTIVE

79 6 Dicembre 2005Stefano Clemente79 Esempio 8: GuestBookView.jsp body { body { font-family: tahoma, helvetica, arial, sans-serif; font-family: tahoma, helvetica, arial, sans-serif; } table, tr, td, th { table, tr, td, th { text-align: center; text-align: center; font-size:.9em; font-size:.9em; border: 3px groove; border: 3px groove; padding: 5px; padding: 5px; background-color: #dddddd; background-color: #dddddd; } Guest List Guest List

80 6 Dicembre 2005Stefano Clemente80 Esempio 8: GuestBookView.jsp Last name Last name First name First name Email Email <% // start scriptlet <% // start scriptlet List guestList = guestData.getGuestList(); List guestList = guestData.getGuestList(); Iterator guestListIterator = guestList.iterator(); Iterator guestListIterator = guestList.iterator(); GuestBean guest; GuestBean guest; while ( guestListIterator.hasNext() ) { while ( guestListIterator.hasNext() ) { guest = ( GuestBean ) guestListIterator.next(); guest = ( GuestBean ) guestListIterator.next(); %> %>

81 6 Dicembre 2005Stefano Clemente81 Esempio 8: GuestBookView.jsp "> "> <% // continue scriptlet <% // continue scriptlet } // end while } // end while %> %> </html>

82 6 Dicembre 2005Stefano Clemente82 Esempio 8: GuestBookErrorPage.jsp <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1- strict.dtd"> "http://www.w3.org/TR/xhtml1/DTD/xhtml1- strict.dtd"> Error! Error! DIRETTIVEDIRETTIVE

83 6 Dicembre 2005Stefano Clemente83 Esempio 8: GuestBookErrorPage.jsp.bigRed {.bigRed { font-size: 2em; font-size: 2em; color: red; color: red; font-weight: bold; font-weight: bold; } <% // scriptlet to determine exception type <% // scriptlet to determine exception type // and output beginning of error message // and output beginning of error message if ( exception instanceof SQLException ) { if ( exception instanceof SQLException ) {

84 6 Dicembre 2005Stefano Clemente84 Esempio 8: GuestBookErrorPage.jsp %> %> An SQLException An SQLException <% } <% } else if ( exception instanceof ClassNotFoundException ) { else if ( exception instanceof ClassNotFoundException ) { %> %> A ClassNotFoundException A ClassNotFoundException <% } <% } else { else { %> %> An exception An exception

85 6 Dicembre 2005Stefano Clemente85 Esempio 8: GuestBookErrorPage.jsp occurred while interacting with the guestbook database. occurred while interacting with the guestbook database. The error message was: The error message was: Please try again later Please try again later </html>

86 6 Dicembre 2005Stefano Clemente86 Esempio 8: File JSP

87 6 Dicembre 2005Stefano Clemente87 Esempio 8: File JavaBean (Plug-in)

88 6 Dicembre 2005Stefano Clemente88 Esempio 8: le direttive per la gestione degli errori La direttiva è una direttiva di pagina che specifica a quale pagina inoltrare la richiesta in caso di errore La direttiva è una direttiva di pagina isErrorPagetrueL’attributo isErrorPage, se settato a true, rende la JSP una pagina di errore exceptionL’effetto è di abilitare la JSP all’accesso all’oggetto implicito exception che contiene le informazioni sull’errore verificatosi

89 6 Dicembre 2005Stefano Clemente89 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 Sono di tre tipi − page − include − taglib

90 6 Dicembre 2005Stefano Clemente90 La direttiva page Specifica delle impostazioni globali della JSP all’interno del JSP-container pagePossono esistere più direttive page purchè ve ne sia solo una per ogni attributo import − l’unica eccezione è l’attributo import che permette alla JSP di importare i package necessari per la sua esecuzione

91 6 Dicembre 2005Stefano Clemente91 La direttiva page

92 6 Dicembre 2005Stefano Clemente92 La direttiva include Include il contenuto di un’altra risorsa, ma solo quando la JSP viene tradotta (a differenza dell’azione ) fileL’unico attributo è file e specifica l’URL della pagina da includere includeL’esempio seguente riscrive l’Esempio 3 sostituendo l’azione con la direttiva include

93 6 Dicembre 2005Stefano Clemente93 Esempio 8: includeDirective.jsp <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> Using the include directive Using the include directive body { body { font-family: tahoma, helvetica, arial, sans-serif; font-family: tahoma, helvetica, arial, sans-serif; } table, tr, td { table, tr, td { font-size:.9em; font-size:.9em; border: 3px groove; border: 3px groove; padding: 5px; padding: 5px; background-color: #dddddd; background-color: #dddddd; }

94 6 Dicembre 2005Stefano Clemente94 Esempio 9: includeDirective.jsp <img src = "images/logotiny.png" <img src = "images/logotiny.png" width = "140" height = "93" width = "140" height = "93" alt = "Deitel & Associates, Inc. Logo" /> alt = "Deitel & Associates, Inc. Logo" /> </html>

95 6 Dicembre 2005Stefano Clemente95 Custom Tag Libraries Permettono di definire dei tag personalizzati attraverso i quali creare contenuti dinamici Tag javax.servlet.jsp.tagext TagSupport BodyTagSupportLa funzionalità è definita nelle classi Java che implementano l’interfaccia Tag javax.servlet.jsp.tagext in genere estendendo la classe TagSupport o BodyTagSupport 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 JavaBean, che pur permettendo di realizzare funzionalità complesse, richiedono agli utilizzatori una certa conoscenza di Java

96 6 Dicembre 2005Stefano Clemente96 Direttiva taglib È la direttiva per l’uso dei custom tag Ha due attributi − uri − uri – specifica l’URI assoluta o relativa del descrittore della libreria di tag − prefix − prefix – specifica il prefisso che serve per distinguere i tag personalizzati dagli altri jspjspx javajavaxservletsunsunwnon è consentito l’uso dei prefissi jsp, jspx, java, javax, servlet, sun e sunw

97 6 Dicembre 2005Stefano Clemente97 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

98 6 Dicembre 2005Stefano Clemente98 Esempio 10

99 6 Dicembre 2005Stefano Clemente99 Esempio 10 – Passo 1 implementazione custom tag: WelcomeTagHandler.java // Fig. 10.31: WelcomeTagHandler.java // Custom tag handler that handles a simple tag. package com.deitel.advjhtp1.jsp.taglibrary; // Java core packages import java.io.*; // Java extension packages import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; public class WelcomeTagHandler extends TagSupport { // Method called to begin tag processing // Method called to begin tag processing public int doStartTag() throws JspException public int doStartTag() throws JspException { // attempt tag processing // attempt tag processing try { try { // obtain JspWriter to output content // obtain JspWriter to output content JspWriter out = pageContext.getOut(); JspWriter out = pageContext.getOut(); // output content // output content out.print( "Welcome to JSP Tag Libraries!" ); out.print( "Welcome to JSP Tag Libraries!" ); } // rethrow IOException to JSP container as JspException // rethrow IOException to JSP container as JspException catch( IOException ioException ) { catch( IOException ioException ) { throw new JspException( ioException.getMessage() ); throw new JspException( ioException.getMessage() ); } return SKIP_BODY; // ignore the tag's body return SKIP_BODY; // ignore the tag's body }}

100 6 Dicembre 2005Stefano Clemente100 Esempio 10 – Passo 2 implementazione custom tag: advjhtp1-taglib.tld <!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN" "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN" "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd"> "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd"> <taglib> 1.0 1.0 1.1 1.1 advjhtp1 advjhtp1 A simple tab library for the examples A simple tab library for the examples welcome welcome com.deitel.advjhtp1.jsp.taglibrary.WelcomeTagHandler com.deitel.advjhtp1.jsp.taglibrary.WelcomeTagHandler empty empty Inserts content welcoming user to tag libraries Inserts content welcoming user to tag libraries ……… spazio per altri tag ……… </taglib>

101 6 Dicembre 2005Stefano Clemente101 Esempio 10: customTagWelcome.jsp Simple Custom Tag Example Simple Custom Tag Example The following text demonstrates a custom tag: The following text demonstrates a custom tag: </html>

102 6 Dicembre 2005Stefano Clemente102 Esempio 10: i file.jsp e.tld

103 6 Dicembre 2005Stefano Clemente103 Esempio 10: la classe

104 6 Dicembre 2005Stefano Clemente104 Esempio 11: custom tag con attributi

105 6 Dicembre 2005Stefano Clemente105 Esempio 11: custom tag con attributi

106 6 Dicembre 2005Stefano Clemente106 Esempio 11: customTagAttribute.jsp Specifying Custom Tag Attributes Specifying Custom Tag Attributes Demonstrating an attribute with a string value Demonstrating an attribute with a string value Demonstrating an attribute with an expression value Demonstrating an attribute with an expression value <% <% String name = request.getParameter( "name" ); String name = request.getParameter( "name" ); %> %> " /> " /> </html>

107 6 Dicembre 2005Stefano Clemente107 Esempio 11: Welcome2TagHandler.java // Fig. 10.34: Welcome2TagHandler.java // Custom tag handler that handles a simple tag. package com.deitel.advjhtp1.jsp.taglibrary; // Java core packages import java.io.*; // Java extension packages import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; public class Welcome2TagHandler extends TagSupport { private String firstName = ""; private String firstName = ""; // Method called to begin tag processing // Method called to begin tag processing public int doStartTag() throws JspException public int doStartTag() throws JspException { // attempt tag processing // attempt tag processing try { try { // obtain JspWriter to output content // obtain JspWriter to output content

108 6 Dicembre 2005Stefano Clemente108 Esempio 11: Welcome2TagHandler.java JspWriter out = pageContext.getOut(); JspWriter out = pageContext.getOut(); // output content // output content out.print( "Hello " + firstName + out.print( "Hello " + firstName + ", Welcome to JSP Tag Libraries!" ); ", Welcome to JSP Tag Libraries!" ); } // rethrow IOException to JSP container as JspException // rethrow IOException to JSP container as JspException catch( IOException ioException ) { catch( IOException ioException ) { throw new JspException( ioException.getMessage() ); throw new JspException( ioException.getMessage() ); } return SKIP_BODY; // ignore the tag's body return SKIP_BODY; // ignore the tag's body } // set firstName attribute to the users first name // set firstName attribute to the users first name public void setFirstName( String username ) public void setFirstName( String username ) { firstName = username; firstName = username; }}

109 6 Dicembre 2005Stefano Clemente109 Esempio 11: advjhtp1-taglib.tld ……………… welcome2 welcome2 com.deitel.advjhtp1.jsp.taglibrary.Welcome2TagHandler com.deitel.advjhtp1.jsp.taglibrary.Welcome2TagHandler empty empty Inserts content welcoming user to tag libraries. Uses Inserts content welcoming user to tag libraries. Uses attribute "name" to insert the user's name. attribute "name" to insert the user's name. firstName firstName true true ………………

110 6 Dicembre 2005Stefano Clemente110 Esempio 11: advjhtp1-taglib.tld attributeL’elemento attribute specifica le caratteristiche degli attributi del tag − name − name indica il nome dell’attributo − requiredtrue false − required indica se l’attributo è richiesto ( true ) o opzionale ( false ) − rtexprvalue true false − rtexprvalue indica se il valore può provenire da un’espressione JSP valutata a run-time ( true ) o se deve essere passato come valore letterale ( false )

111 6 Dicembre 2005Stefano Clemente111 Esempio 11: i file.jsp e.tld

112 6 Dicembre 2005Stefano Clemente112 Esempio 11: la classe

113 6 Dicembre 2005Stefano Clemente113 Esempio 12: interazione con il body

114 6 Dicembre 2005Stefano Clemente114 Esempio 12: customTagBody.jsp Guest List Guest List body { body { font-family: tahoma, helvetica, arial, sans-serif font-family: tahoma, helvetica, arial, sans-serif } table, tr, td, th { table, tr, td, th { text-align: center; text-align: center; font-size:.9em; font-size:.9em; border: 3px groove; border: 3px groove; padding: 5px; padding: 5px; background-color: #dddddd background-color: #dddddd }

115 6 Dicembre 2005Stefano Clemente115 Esempio 12: customTagBody.jsp Guest List Guest List Last name Last name First name First name Email Email "> "> </html>

116 6 Dicembre 2005Stefano Clemente116 Esempio 12: customTagBody.jsp Si osservi che guestlist − le espressioni JSP dell’elemento guestlist usano variabili non definite nella JSP queste variabili sono definite dal gestore del tag quando il tag è utilizzato PageContextle variabili sono definite nel PageContext 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

117 6 Dicembre 2005Stefano Clemente117 Esempio 12: GuestBookTag.java GuestDataBeanIl gestore del tag istanzia GuestDataBean per l’accesso al DB GuestBookTag BodyTagSupport BodyTagGuestBookTag estende la classe BodyTagSupport che contiene i metodi dell’interfaccia BodyTag − doInitBody doStartTag doAfterBodyrichiamato una sola volta dopo doStartTag e prima di doAfterBody doStartTagTag.SKIP_BODYse doStartTag restituisce Tag.SKIP_BODY, non viene richiamato − doAfterBody Tag.EVAL_BODY_TAGrichiamato tutte le volte che occorrono per elaborare il corpo del tag, ogni volta che viene restituito un Tag.EVAL_BODY_TAG Tag.SKIP_BODYdopo un Tag.SKIP_BODY non viene più richiamato

118 6 Dicembre 2005Stefano Clemente118 Esempio 12: GuestBookTag.java // Fig. 10.37: GuestBookTag.java // Custom tag handler that reads information from the guestbook // database and makes that data available in a JSP. package com.deitel.advjhtp1.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.advjhtp1.jsp.beans.*; public class GuestBookTag extends BodyTagSupport { private String firstName; private String firstName; private String lastName; private String lastName; private String email; private String email; private GuestDataBean guestData; private GuestDataBean guestData; private GuestBean guest; private GuestBean guest;

119 6 Dicembre 2005Stefano Clemente119 Esempio 12: GuestBookTag.java private Iterator iterator; private Iterator iterator; // Method called to begin tag processing // Method called to begin tag processing public int doStartTag() throws JspException public int doStartTag() throws JspException { // attempt tag processing // attempt tag processing try { try { guestData = new GuestDataBean(); guestData = new GuestDataBean(); List list = guestData.getGuestList(); List list = guestData.getGuestList(); iterator = list.iterator(); iterator = list.iterator(); if ( iterator.hasNext() ) { if ( iterator.hasNext() ) { processNextGuest(); processNextGuest(); return EVAL_BODY_TAG; // continue body processing return EVAL_BODY_TAG; // continue body processing } else else return SKIP_BODY; // terminate body processing return SKIP_BODY; // terminate body processing } // if any exceptions occur, do not continue processing // if any exceptions occur, do not continue processing // tag's body // tag's body catch ( Exception exception ) { catch ( Exception exception ) {

120 6 Dicembre 2005Stefano Clemente120 Esempio 12: GuestBookTag.java exception.printStackTrace(); exception.printStackTrace(); return SKIP_BODY; // ignore the tag's body return SKIP_BODY; // ignore the tag's body } } // process body and determine if body processing // process body and determine if body processing // should continue // should continue public int doAfterBody() public int doAfterBody() { // attempt to output body data // attempt to output body data try { try { bodyContent.writeOut( getPreviousOut() ); bodyContent.writeOut( getPreviousOut() ); } // if exception occurs, terminate body processing // if exception occurs, terminate body processing catch ( IOException ioException ) { catch ( IOException ioException ) { ioException.printStackTrace(); ioException.printStackTrace(); return SKIP_BODY; // terminate body processing return SKIP_BODY; // terminate body processing } bodyContent.clearBody(); bodyContent.clearBody(); if ( iterator.hasNext() ) { if ( iterator.hasNext() ) {

121 6 Dicembre 2005Stefano Clemente121 Esempio 12: GuestBookTag.java processNextGuest(); processNextGuest(); return EVAL_BODY_TAG; // continue body processing return EVAL_BODY_TAG; // continue body processing } else else return SKIP_BODY; // terminate body processing return SKIP_BODY; // terminate body processing } // obtains the next GuestBean and extracts its data // obtains the next GuestBean and extracts its data private void processNextGuest() private void processNextGuest() { // get next guest // get next guest guest = ( GuestBean ) iterator.next(); guest = ( GuestBean ) iterator.next(); pageContext.setAttribute( pageContext.setAttribute( "firstName", guest.getFirstName() ); "firstName", guest.getFirstName() ); pageContext.setAttribute( pageContext.setAttribute( "lastName", guest.getLastName() ); "lastName", guest.getLastName() ); pageContext.setAttribute( pageContext.setAttribute( "email", guest.getEmail() ); "email", guest.getEmail() ); }}

122 6 Dicembre 2005Stefano Clemente122 Esempio 12: GuestBookTagExtraInfo.java processNextGuest PagesContext.setAttributeprocessNextGuest usa PagesContext.setAttribute per specificare il nome e il valore di ogni attributo Il JSP container si fa carico di creare le variabili utilizzate nella JSP PageContext − non può creare le variabili nel PageContext a meno che non conosca il nome e il tipo delle variabili ExtraInfoPer specificare queste informazioni occorre definire una classe con lo stesso nome del gestore del tag e con ExtraInfo alla fine − GuestBookTagExtraInfo.class

123 6 Dicembre 2005Stefano Clemente123 Esempio 12: GuestBookTagExtraInfo.java ExtraInfoTagExtraInfo javax.servlet.jsp.tagextExtraInfo estende la classe TagExtraInfo del package javax.servlet.jsp.tagext TagExtraInfoIl container usa le informazioni specificate da una sottoclasse di TagExtraInfo per determinare le variabili da creare getVariableInfoPer specificare le variabili bisogna definire il metodo getVariableInfo in override al metodo ereditato dalla classe VariableInfo PageContext − questo metodo restituisce un array di oggetti VariableInfo che il container utilizzerà per creare le nuove variabili nel PageContext o per autorizzare il custom tag a utilizzarne di esistenti

124 6 Dicembre 2005Stefano Clemente124 Esempio 12: GuestBookTagExtraInfo.java VariableInfoIl costruttore VariableInfo accetta quattro argomenti String − il nome della variabile – String String − il nome della classe alla quale appartiene la variabile (tipo di dati) – String − boolean truetrue – il container dovrà creare la variabile falsefalse – altrimenti static − portata della variabile nella JSP – intero static NESTEDNESTED – la variabile può essere usata solo nel corpo del custom tag AT_BEGINAT_BEGIN – la variabile può essere usata ovunque nella JSP dopo a partire dal tag di apertura del custom tag AT_ENDAT_END – la variabile può essere usata ovunque nella JSP dopo a partire dal tag di chiusura del custom tag

125 6 Dicembre 2005Stefano Clemente125 Esempio 12: GuestBookTagExtraInfo.java // Fig.10.38: GuestBookTagExtraInfo.java // Class that defines the variable names and types created by // custom tag handler GuestBookTag. package com.deitel.advjhtp1.jsp.taglibrary; // Java core packages import javax.servlet.jsp.tagext.*; public class GuestBookTagExtraInfo extends TagExtraInfo { // method that returns information about the variables // method that returns information about the variables // GuestBookTag creates for use in a JSP // GuestBookTag creates for use in a JSP public VariableInfo [] getVariableInfo( TagData tagData ) public VariableInfo [] getVariableInfo( TagData tagData ) { VariableInfo firstName = new VariableInfo( "firstName", VariableInfo firstName = new VariableInfo( "firstName", "String", true, VariableInfo.NESTED ); "String", true, VariableInfo.NESTED ); VariableInfo lastName = new VariableInfo( "lastName", VariableInfo lastName = new VariableInfo( "lastName", "String", true, VariableInfo.NESTED ); "String", true, VariableInfo.NESTED ); VariableInfo email = new VariableInfo( "email", VariableInfo email = new VariableInfo( "email", "String", true, VariableInfo.NESTED ); "String", true, VariableInfo.NESTED ); VariableInfo varableInfo [] = VariableInfo varableInfo [] = { firstName, lastName, email }; { firstName, lastName, email }; return varableInfo; return varableInfo; }}

126 6 Dicembre 2005Stefano Clemente126 Esempio 12: advjhtp1-taglib.tld ……………… <tag> guestlist guestlist com.deitel.advjhtp1.jsp.taglibrary.GuestBookTag com.deitel.advjhtp1.jsp.taglibrary.GuestBookTag com.deitel.advjhtp1.jsp.taglibrary.GuestBookTagExtraInfo com.deitel.advjhtp1.jsp.taglibrary.GuestBookTagExtraInfo JSP JSP Iterates over a list of GuestBean objects Iterates over a list of GuestBean objects </tag>………………

127 6 Dicembre 2005Stefano Clemente127 Esempio 12: i file.jsp e.tld

128 6 Dicembre 2005Stefano Clemente128 Esempio 11: la classe

129 6 Dicembre 2005Stefano Clemente129 Esempio 12: i JavaBeans


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

Presentazioni simili


Annunci Google