Tecnologie di Internet (CLEI) A.A. 2003-04

Download Report

Transcript Tecnologie di Internet (CLEI) A.A. 2003-04

Tecnologie lato Server:
JSP (Java Server Pages)
Stefano Clemente
[email protected]
© 2005 Stefano Clemente
I lucidi sono in parte realizzati con materiale tratto dal libro di testo adottato tradotto in italiano:
© 2002 Prentice Hall
H. M. Deitel, P. J. Deitel, T. R. Nieto
Internet & World Wide Web – How To Program (Second Edition)
Riferimenti bibliografici
• H. M. Deitel, P. J. Deitel, T. R. Nieto
Internet & World Wide Web – How
To Program (Second Edition)
ed. Prentice Hall 2002
Capitolo 31 (sul CD allegato al libro)
• http://java.sun.com/developer/onlineTra
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 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
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 B2B 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 JavaServer 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 eLEmenTS)
− 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
− jspInit
− jspService
− jspDestroy
6 Dicembre 2005
Stefano Clemente
8
Esempio 1
6 Dicembre 2005
Stefano Clemente
9
Esempio 1: clock.jsp
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- Fig. 10.1: clock.jsp -->
<html xmlns = "http://www.w3.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: 2em; }
</style>
</head>
6 Dicembre 2005
Stefano Clemente
10
Esempio 1: clock.jsp
<body>
<p class = "big">Simple JSP Example</p>
<table style = "border: 6px 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
Oggetto Implicito
Descrizione
Application
application
Oggetto javax.servlet.ServletContext che rappresenta il contenitore nel quale la JSP è
eseguita
Page Scope
config
exception
out
page
pageContext
response
Oggetto javax.servlet.ServletConfig che rappresenta le opzioni di configurazione di JSP.
Oggetto java.lang.Throwable che rappresenta l’eccezione passata alla pagina di errore JSP.
Disponibile solo nella pagina di errore JSP.
Oggetto javax.servlet.jsp.JspWriter che scrive testo come parte della risposta a una
richiesta. È usato in modo implicito con le espressioni JSP e le azioni che inseriscono stringhe nella
risposta.
Oggetto java.lang.Object che rappresenta il riferimento this nell’istanza corrente.
Oggetto javax.servlet.jsp.PageContext che nasconde i dettagli implementativi dei
contenitori servlet e JSP, ma permette l’accesso agli oggetti impliciti da parte dei programmatori.
Questo oggetto è la risposta al client. È solitamente un’istanza dell’oggetto HttpServletResponse
(package javax.servlet.http). Nel caso in cui venga usato un protocollo diverso da HTTP,
questo oggetto è l’istanza di una classe che implementa javax.servlet.ServletResponse.
Request Scope
request
Questo oggetto rappresenta la richiesta del client. Normalmente è un’istanza della classe che
implementa HttpServletRequest (package javax.servlet.http). Nel caso venga usato un
protocollo diverso da HTTP è un’istanza della sottoclasse javax.servlet.ServletRequest.
Session Scope
session
6 Dicembre 2005
Oggetto javax.servlet.http.HttpSession che rappresenta le informazioni della sessione del
client se una sessione è stata creata. Disponibile solo nelle pagine che partecipano a una sessione.
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 "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- Fig. 10.4: welcome.jsp -->
<!-- JSP that processes a "get" request containing data. -->
<html xmlns = "http://www.w3.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.getParameter( "firstName" );
if ( name != null ) {
%> <%-- end scriptlet to insert fixed template data --%>
<h1>
Hello <%= name %>, <br />
6 Dicembre 2005
Stefano Clemente
18
Esempio 1: welcome.jsp
Welcome to JavaServer Pages!
</h1>
<% // 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 = "firstName" />
<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 JavaBeans
• 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
Azione
Descrizione
<jsp:include>
Include dinamicamente un’altra risorsa in una JSP. Quando la JSP è eseguita la risorsa
riferita viene inclusa e elaborata.
Inoltra una richiesta a un’altra JSP, servlet o pagina statica. L’azione termina
l’esecuzione della JSP corrente.
Permette di includere un plug-in in una pagina sotto forma di un object specifico del
browser o di un elemento embed HTML. Nel caso di applet Java, l’azione abilita il
<jsp:forward>
<jsp:plugin>
<jsp:param>
download e l’installazione del Java Plug-in, se non già installato sul client.
Usato con le azioni include, forward e plugin per specificare coppie di
informazioni addizionali del tipo nome/valore da usare con queste azioni.
Manipolazione di JavaBean
<jsp:useBean>
<jsp:setProperty>
<jsp:getProperty>
6 Dicembre 2005
Specifica che la JSP usa un’istanza JavaBean. Quest’azione specifica la portata del
bean e assegna a esso un ID che i componenti di scripting possono utilizzare per
manipolare il bean.
Imposta le proprietà dell’istanza JavaBean specificata. Una caratteristica di
quest’azione è il matcheiing automatico dei parametri con le propreità del bean aventi
lo stesso nome.
Riceve una proprietà dall’istanza JavaBean e converte il risultato in una stringa per
l’uso nella risposta al client.
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
− clock2.jsp
• In particolare include.jsp è una tabella che:
− nella parte alta mostra banner.html
− a sinistra mostra toc.html
− a destra mostra clock2.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: 580px">
<p>
Java(TM), C, C++, Visual Basic(R),
Object Technology, and <br /> Internet and
World Wide Web Programming Training&nbsp;<br />
On-Site Seminars Delivered Worldwide
</p>
<p>
<a href = "mailto:[email protected]">
[email protected]</a><br />
978.579.9911<br />
490B 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/BookStore
</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:[email protected]">
[email protected]
</a><br />
Copyright 1995-2002 by Deitel &amp; Associates, Inc.
All Rights Reserved.
</p>
6 Dicembre 2005
Stefano Clemente
27
Esempio 3: clock2.jsp
<!-- Fig. 10.9: clock2.jsp
-->
<!-- date and time to include in another
document -->
<table>
<tr>
<td style = "background-color: black;">
<p class = "big" style = "color: cyan;
font-size: 3em;
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 "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- Fig. 10.7: include.jsp -->
<html xmlns = "http://www.w3.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: .9em;
border: 3px groove;
padding: 5px;
background-color: #dddddd;
}
</style>
</head>
<body>
<table>
<tr>
<td style = "width: 160px; textalign: center">
<img src = "images/logotiny.png"
width = "140" height = "93"
6 Dicembre 2005
Stefano Clemente
30
Esempio 3: include.jsp
/>
alt = "Deitel & Associates, Inc. Logo"
</td>
<td>
<%-- include banner.html in this JSP --%>
<jsp:include page = "banner.html"
flush = "true" />
</td>
</tr>
<tr>
<td style = "width: 160px">
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 clock2.jsp in this JSP --%>
<jsp:include page = "clock2.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: forward1.jsp
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- Fig. 10.11: forward1.jsp -->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Forward request to another JSP</title>
</head>
<body>
<% // begin scriptlet
String name = request.getParameter( "firstName" );
if ( name != null ) {
%> <%-- end scriptlet to insert fixed template data --%>
<jsp:forward page = "forward2.jsp">
<jsp:param name = "date"
value = "<%= new java.util.Date() %>" />
</jsp:forward>
6 Dicembre 2005
Stefano Clemente
35
Esempio 4: forward1.jsp
<% // continue scriptlet
} // end if
else {
%> <%-- end scriptlet to insert fixed template data --%>
<form action = "forward1.jsp" method = "get">
<p>Type your first name and press Submit</p>
<p><input type = "text" name = "firstName" />
<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: forward2.jsp
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- forward2.jsp -->
<html xmlns = "http://www.w3.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: 2em;
}
</style>
</head>
6 Dicembre 2005
Stefano Clemente
37
Esempio 4: forward2.jsp
<body>
<p class = "big">
Hello <%= request.getParameter( "firstName" ) %>,
<br />
Your request was received <br /> and forwarded at
</p>
<table style = "border: 6px outset;">
<tr>
<td style = "background-color: black;">
<p class = "big" style = "color: cyan;">
<%= request.getParameter( "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: forward3.jsp
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- Fig. 10.11: forward3.jsp -->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Forward request to another JSP</title>
</head>
<body>
<% // begin scriptlet
String name = request.getParameter( "firstName" );
if ( name != null ) {
%> <%-- end scriptlet to insert fixed template data --%>
<jsp:forward page = "forward2.jsp">
<jsp:param name = "firstName"
value = "Pippo" />
<jsp:param name = "date"
value = "<%= new java.util.Date() %>" />
</jsp:forward>
6 Dicembre 2005
Stefano Clemente
41
Esempio 5: forward3.jsp
<% // continue scriptlet
} // end if
else {
%> <%-- end scriptlet to insert fixed template data --%>
<form action = "forward3.jsp" method = "get">
<p>Type your first name and press Submit</p>
<p><input type = "text" name = "firstName" />
<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 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”
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à
Attributo
Descrizione
type
code
codebase
align
archive
Tipo del plug-in: bean o applet
Classe del plug-in
Locazione della classe specificata con code o degli archivi specificati con archive
Allineamento
Una lista di nomi di file archivio separati da spazi. Questi file contengono risorse
usate dal plug-in. Un archivio può inccludere anche la classe specificata con code
(cfr. applet – TecnInt8.pdf).
Altezza del plug-in nella pagina (pixel o percentuale).
Spazio in pixel a destra e a sinistra della componente.
Versione di Java Runtime Environment e plug-in richiesti per eseguire il plug-in. Il
valore di default è 1.1.
Nome del plug-in.
Spazio in pixel al di sopra e al di sotto del plug-in.
Descrizione del plug-in.
Ampiezza del plug-in nella pagina (pixel o percentuale).
Locazione per il download del plug-in Java per Netscape Navigator.
Locazione per il download del plug-in Java per Internet Explorer.
height
hspace
jreversion
name
vspace
title
width
nspluginurl
iepluginurl
6 Dicembre 2005
Stefano Clemente
45
Esempio 6
Applet
6 Dicembre 2005
Stefano Clemente
46
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
public void init()
{
// obtain color parameters from XHTML file
6 Dicembre 2005
Stefano Clemente
47
Esempio 6: ShapesApplet.java
try {
int red = Integer.parseInt( getParameter( "red" ) );
int green = Integer.parseInt( getParameter( "green" ) );
int blue = Integer.parseInt( getParameter( "blue" ) );
Color backgroundColor = new Color( red, green, blue );
}
setBackground( backgroundColor );
// if there is an exception while processing the color
// parameters, catch it and ignore it
catch ( Exception exception ) {
// do nothing
}
}
public void paint( Graphics g )
{
6 Dicembre 2005
Stefano Clemente
48
Esempio 6: ShapesApplet.java
// create arrays of x and y coordinates
int xPoints[] =
{ 55, 67, 109, 73, 83, 55, 27, 37, 1, 43 };
int yPoints[] =
{ 0, 36, 36, 54, 96, 72, 96, 54, 36, 36 };
// obtain reference to a Graphics2D object
Graphics2D g2d = ( Graphics2D ) g;
// create a star from a series of points
GeneralPath star = new GeneralPath();
// set the initial coordinate of the GeneralPath
star.moveTo( xPoints[ 0 ], yPoints[ 0 ] );
// create the star--this does not draw the star
for ( int k = 1; k < xPoints.length; k++ )
star.lineTo( xPoints[ k ], yPoints[ k ] );
6 Dicembre 2005
Stefano Clemente
49
Esempio 6: ShapesApplet.java
// close the shape
star.closePath();
// translate the origin to (200, 200)
g2d.translate( 200, 200 );
// rotate around origin and draw stars in random colors
for ( int j = 1; j <= 20; j++ ) {
g2d.rotate( Math.PI / 10.0 );
g2d.setColor(
new Color( ( int ) ( Math.random() * 256 ),
( int ) ( Math.random() * 256 ),
( int ) ( Math.random() * 256 ) ) );
}
}
}
6 Dicembre 2005
g2d.fill( star );
// 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.advjhtp1.jsp.applet.ShapesApplet"
codebase = "/advjhtp1/jsp"
width = "400"
height = "400">
<jsp:params>
<jsp:param name = "red" value = "255" />
<jsp:param name = "green" value = "255" />
<jsp:param name = "blue" value = "0" />
</jsp:params>
</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
Attributo
Descrizione
id
Il nome che sarà usato per manipolare l’oggetto Java attraverso le azioni
<jsp:setProperty> e <jsp:getProperty>. Una variabile con questo nome è anche
dichiarata per l’uso negli script delle JSP. Il nome è case-sensitive.
scope
La portata dell’oggetto Java (page, request, session o application). La portata di default
è page.
class
Il nome completo della classe dell’oggetto Java.
beanName
Il nome del bean che può essere usato con il metodo instantiate della classe
java.beans.Beans per caricare un JavaBean in memoria.
type
Il tipo del JavaBean. Può essere dello stesso tipo dell’attributo class, una super-classe di quel
tipo o un’interfaccia implementata da quel tipo. Il valore di default è lo stesso dell’attributo
class. Se l’oggetto Java non è dello stesso tipo specificato con l’attributo type, viene
generata un’eccezione ClassCastException
6 Dicembre 2005
Stefano Clemente
55
<jsp:usebean>
• Se non vengono specificati gli attributi class
e beanName, 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, request, 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 JavaBean that rotates advertisements.
package com.deitel.advjhtp1.jsp.beans;
public class Rotator {
private String images[] = { "images/jhtp3.jpg",
"images/xmlhtp1.jpg", "images/ebechtp1.jpg",
"images/iw3htp1.jpg", "images/cpphtp3.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/013028419X/"
"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 selectedIndex = 0;
// returns image file name for current ad
public String getImage()
{
return images[ selectedIndex ];
}
// returns the URL for ad's corresponding Web site
public String getLink()
{
return links[ selectedIndex ];
}
}
// update selectedIndex so next calls to getImage and
// getLink return a different advertisement
public void nextAd()
{
selectedIndex = ( selectedIndex + 1 ) % images.length;
}
6 Dicembre 2005
Stefano Clemente
59
Esempio 7: adrotator.jsp
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- Fig. 10.18: adrotator.jsp -->
<jsp:useBean id = "rotator" scope = "session"
class = "com.deitel.advjhtp1.jsp.beans.Rotator" />
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>AdRotator Example</title>
<style type = "text/css">
.big { font-family: helvetica, arial, sansserif;
font-weight: bold;
font-size: 2em; }
6 Dicembre 2005
Stefano Clemente
60
Esempio 7: adrotator.jsp
</style>
<%-- update advertisement --%>
<% rotator.nextAd(); %>
</head>
<body>
<p class = "big">AdRotator Example</p>
<p>
<a href = "<jsp:getProperty name = "rotator"
property = "link" />">
<img src = "<jsp:getProperty name = "rotator"
property = "image" />" alt =
"advertisement" />
</a>
</p>
</body>
</html>
6 Dicembre 2005
Stefano Clemente
61
Esempio 7: adrotator1.jsp
</style>
<%-- update advertisement --%>
<% rotator.nextAd(); %>
</head>
<body>
<p class = "big">AdRotator Example</p>
<p>
<a href = "<%= rotator.getLink() %>">
<img src = "<%= rotator.getImage() %>"
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 JavaBean (Plug-in)
6 Dicembre 2005
Stefano Clemente
64
<jsp:getProperty>
• 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:getProperty name = "abc" property = "xyz"
/>
cerca di invocare getXyz dall’oggetto abc
• Equivale a scrivere l’espressione JSP
<%= abc.getXyz() %>
6 Dicembre 2005
Stefano Clemente
65
<jsp:setProperty>
• Serve per settare valori nel bean
Attributo
Descrizione
name
L’ID del JavaBean del quale si vuole settare una o più proprietà.
property Il nome della proprietà che si vuole settare. Assegnando a questo attributo il valore "*", JSP confronta I
parametri della richiesta con quelli del bean: per ogni parametro che corrisponde (per esempio il nome del
parametro della richiesta è identico al nome della proprietà del bean) la corrispondente proprietà del bean
viene settata; se il valore del parametro della richiesta è “” il valore della proprietà del bean rimane
invariato.
param
Se i nomi dei parametri della richiesta non corrispondono ai nomi delle proprietà del bean, questo attributo
serve per specificare quale parametro della richiesta deve essere usato per settare la specifica proprietà
del bean. È un attributo opzionale. Se omesso, i nomi dei parametri della richiesta devono corrispondere a
quelli delle proprietà del bean
value
Valore da assegnare alla proprietà del bean. Il valore è in genere il risultato di un’espressione JSP. Questo
attributo è utile per settare proprietà del bean non settabili attraverso i parametri della richiesta. È opzionale
e se omesso la proprietà del JavaBean deve essere di un tipo di dati che può essere settato con i
parametri della richiesta.
6 Dicembre 2005
Stefano Clemente
66
Esempio 8
1
2
6 Dicembre 2005
Stefano Clemente
67
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;
// set the guest's first name
public void setFirstName( String name )
{
firstName = name;
}
// get the guest's first name
public String getFirstName()
{
return firstName;
}
// set the guest's last name
public void setLastName( String name )
6 Dicembre 2005
Stefano Clemente
68
Esempio 8: GuestBean.java
{
}
lastName = name;
// get the guest's last name
public String getLastName()
{
return lastName;
}
// set the guest's email address
public void setEmail( String address )
{
email = address;
}
}
// get the guest's email address
public String getEmail()
{
return email;
}
6 Dicembre 2005
Stefano Clemente
69
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 PreparedStatement addRecord, getRecords;
// construct TitlesBean object
public GuestDataBean() throws Exception
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String filename = "c:/web/advjhtp1/guestbook.mdb";
String database = "jdbc:odbc:Driver={Microsoft Access Driver "
+ "(*.mdb)};DBQ=";
database+= filename.trim() + ";DriverID=22;READONLY=true}";
6 Dicembre 2005
Stefano Clemente
70
Esempio 8: GuestDataBean.java
connection = DriverManager.getConnection( database ,"","");
getRecords =
connection.prepareStatement(
"SELECT firstName, lastName, email FROM guests"
);
addRecord =
connection.prepareStatement(
"INSERT INTO guests ( " +
"firstName, lastName, email ) " +
"VALUES ( ?, ?, ? )"
);
}
// return an ArrayList of GuestBeans
public List getGuestList() throws SQLException
{
List guestList = new ArrayList();
// obtain list of titles
6 Dicembre 2005
Stefano Clemente
71
Esempio 8: GuestDataBean.java
ResultSet results = getRecords.executeQuery();
// get row data
while ( results.next() ) {
GuestBean guest = new GuestBean();
guest.setFirstName( results.getString( 1 ) );
guest.setLastName( results.getString( 2 ) );
guest.setEmail( results.getString( 3 ) );
}
}
guestList.add( guest );
return guestList;
// insert a guest in guestbook database
public void addGuest( GuestBean guest ) throws SQLException
{
addRecord.setString( 1, guest.getFirstName() );
addRecord.setString( 2, guest.getLastName() );
6 Dicembre 2005
Stefano Clemente
72
Esempio 8: GuestDataBean.java
addRecord.setString( 3, guest.getEmail() );
}
addRecord.executeUpdate();
// close statements and terminate database connection
protected void finalize()
{
// attempt to close database connection
try {
getRecords.close();
addRecord.close();
connection.close();
}
}
}
// process SQLException on close operation
catch ( SQLException sqlException ) {
sqlException.printStackTrace();
}
6 Dicembre 2005
Stefano Clemente
73
Esempio 8: GuestBookLogin.jsp
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> DIRETTIVA
<!-- Fig. 10.22: guestBookLogin.jsp -->
<%-- page settings --%>
<%@ page errorPage = "guestBookErrorPage.jsp" %>
<%-- beans used in this JSP --%>
<jsp:useBean id = "guest" scope = "page"
class = "com.deitel.advjhtp1.jsp.beans.GuestBean" />
<jsp:useBean id = "guestData" scope = "request"
class = "com.deitel.advjhtp1.jsp.beans.GuestDataBean" />
<html xmlns = "http://www.w3.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: GuestBookLogin.jsp
table, tr, td {
font-size: .9em;
border: 3px groove;
padding: 5px;
background-color: #dddddd;
}
</style>
</head>
<body>
<jsp:setProperty name = "guest" property = "*" />
<% // start scriptlet
if ( guest.getFirstName() == null ||
guest.getLastName() == null ||
guest.getEmail() == null ) {
%> <%-- end scriptlet to insert fixed template data --%>
<form method = "post" action = "guestBookLogin.jsp">
<p>Enter your first name, last name and email
address to register in our guest book.</p>
<table>
<tr>
6 Dicembre 2005
Stefano Clemente
75
Esempio 8: GuestBookLogin.jsp
<td>First name</td>
<td>
<input type = "text" name = "firstName" />
</td>
</tr>
<tr>
<td>Last name</td>
<td>
<input type = "text" name = "lastName" />
</td>
</tr>
<tr>
<td>Email</td>
<td>
<input type = "text" name = "email" />
</td>
</tr>
<tr>
<td colspan = "2">
6 Dicembre 2005
Stefano Clemente
76
Esempio 8: GuestBookLogin.jsp
<input type = "submit"
value = "Submit" />
</td>
</tr>
</table>
</form>
<% // continue scriptlet
} // end if
else {
guestData.addGuest( guest );
%> <%-- end scriptlet to insert jsp:forward action --%>
<%-- forward to display guest book contents --%>
<jsp:forward page = "guestBookView.jsp" />
<% // continue scriptlet
}
// end else
%> <%-- end scriptlet --%>
</body>
</html>
6 Dicembre 2005
Stefano Clemente
77
Esempio 8: GuestBookView.jsp
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
DIRETTIVE
<!-- Fig. 10.23: guestBookView.jsp -->
<%-- page settings --%>
<%@ page errorPage = "guestBookErrorPage.jsp" %>
<%@ page import = "java.util.*" %>
<%@ page import = "com.deitel.advjhtp1.jsp.beans.*" %>
<%-- GuestDataBean to obtain guest list --%>
<jsp:useBean id = "guestData" scope = "request"
class = "com.deitel.advjhtp1.jsp.beans.GuestDataBean"
/>
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Guest List</title>
6 Dicembre 2005
Stefano Clemente
78
Esempio 8: GuestBookView.jsp
<style type = "text/css">
body {
font-family: tahoma, helvetica, arial, sans-serif;
}
table, tr, td, th {
text-align: center;
font-size: .9em;
border: 3px groove;
padding: 5px;
background-color: #dddddd;
}
</style>
</head>
<body>
<p style = "font-size: 2em;">Guest List</p>
<table>
<thead>
<tr>
6 Dicembre 2005
Stefano Clemente
79
Esempio 8: GuestBookView.jsp
<th style = "width: 100px;">Last name</th>
<th style = "width: 100px;">First name</th>
<th style = "width: 200px;">Email</th>
</tr>
</thead>
<tbody>
<% // start scriptlet
List guestList = guestData.getGuestList();
Iterator guestListIterator = guestList.iterator();
GuestBean guest;
while ( guestListIterator.hasNext() ) {
guest = ( GuestBean ) guestListIterator.next();
%> <%-- end scriptlet; insert fixed template data --%>
<tr>
6 Dicembre 2005
Stefano Clemente
80
Esempio 8: GuestBookView.jsp
<td><%= guest.getLastName() %></td>
<td><%= guest.getFirstName() %></td>
<td>
<a href = "mailto:<%= guest.getEmail() %>">
<%= guest.getEmail() %></a>
</td>
</tr>
<% // continue scriptlet
} // end while
%> <%-- end scriptlet --%>
</tbody>
</table>
</body>
</html>
6 Dicembre 2005
Stefano Clemente
81
Esempio 8:
GuestBookErrorPage.jsp
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1strict.dtd">
<!-- Fig. 10.24: guestBookErrorPage.jsp -->
<%-- page settings --%>
<%@ page isErrorPage = "true" %>
<%@ page import = "java.util.*" %>
<%@ page import = "java.sql.*" %>
DIRETTIVE
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Error!</title>
6 Dicembre 2005
Stefano Clemente
82
Esempio 8:
GuestBookErrorPage.jsp
<style type = "text/css">
.bigRed {
font-size: 2em;
color: red;
font-weight: bold;
}
</style>
</head>
<body>
<p class = "bigRed">
<% // scriptlet to determine exception type
// and output beginning of error message
if ( exception instanceof SQLException ) {
6 Dicembre 2005
Stefano Clemente
83
Esempio 8:
GuestBookErrorPage.jsp
%>
An SQLException
<% }
else if ( exception instanceof
ClassNotFoundException ) {
%>
A ClassNotFoundException
<% }
else {
%>
An exception
6 Dicembre 2005
Stefano Clemente
84
Esempio 8:
GuestBookErrorPage.jsp
%>
<%-- end scriptlet to insert fixed template data --
<%-- continue error message output --%>
occurred while interacting with the guestbook
database.
<% } %>
</p>
<p class = "bigRed">
The error message was:<br />
<%= exception.getMessage() %>
</p>
<p class = "bigRed">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 JavaBean (Plug-in)
6 Dicembre 2005
Stefano Clemente
87
Esempio 8: le direttive per la
gestione degli errori
• La direttiva
<%@ page errorPage = "guestBookErrorPage.jsp" %>
è una direttiva di pagina che specifica a quale pagina inoltrare la
richiesta in caso di errore
• La direttiva
<%@ page isErrorPage = "true" %>
è una direttiva di pagina
• L’attributo isErrorPage, se settato a 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
Attributo
Descrizione
language
extends
Linguaggio di scripting usato nella JSP. Attualmente l’unico valore possibile è java.
Specifica la classe dalla quale la JSP tradotta sarà ereditata. Deve essere un nome
completo di package e classe.
Specifica un elenco di nomi di classi e/o package sparati da virgole che la JSP corrente
utilizzerà. Se il linguaggio di scripting è java, per default l’elenco importato è
java.lang.*, javax.servlet.*, javax.servlet.jsp.* e
javax.servlet.http.*. Se vengono specificate più import, i nomi dei package
sono trasformati in un elenco dal JSP-container
Specifica se la pagina farà parte di una sessione. I valori possibili sono true (default –
partecipa a una sessione) o false (non partecipa). Se la pagina è parte di una sessione,
l’oggetto implicito session è utilizzabile nella pagina. In caso contrario, session non è
disponibile e il suo uso
comporta un errore al momento della traduzione della JSP.
Stefano Clemente
90
import
session
6 Dicembre 2005
La direttiva page
Attributo
Descrizione
buffer
Specifica la dimensione del buffer di output usato con l’oggetto implicito out. Può valere
none quando non si vuole usare un buffer, o un valore del tipo 8kb (dimensione di
default). La specifica di JSP dice che bisogna usare un buffer almeno pari alla
dimensione di default.
Se settato al valore di default, true, indica che il bufferspecificato con out deve essere
svuotato automaticamente quando si riempie. Se false, si verificherà un errore in caso
di overflow del buffer. Deve essere settato a true se buffer vale none.
Specifica se la pagina è thread safe. Se true (default), la pagina è considerata thread
safe, e può elaborare più richieste contemporaneamente. Se false, la servlet relativa
alla pagina implementa l’interfaccia java.lang.SingleThreadModel e verrà accettata
una sola richiesta alla volta. Lo standard JSP permette più istanze delle JSP non thread
safe, in modo che il container possa gestire le richieste in modo più efficiente.
Specifica una descrizione della pagina. Si può accedere a questa informazione attraverso
il metodo getServletInfo della servlet che rappresenta la traduzione della JSP. Il
metodo è invocabile attraverso l’oggetto implicito page.
È la pagina alla quale verranno inviate le eccezioni. L’oggetto implicito exception
conterrà l’eccezione.
Specifica se la pagina è una pagina per la gestione degli errori. Se settato a true, sarà
creato l’oggetto implicito exception contenente i riferimenti all’eccezione, mentre se
settato a false (default), l’uso dell’oggetto exception nella JSP provocherà un errore
durante la traduzione.
Specifica il tipo MIME della risposta. Il default è text/html.
autoFlush
isThreadSafe
info
errorPage
isErrorPage
contentType
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>)
• 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: includeDirective.jsp
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- Fig. 10.28: includeDirective.jsp -->
<html xmlns = "http://www.w3.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: .9em;
border: 3px groove;
padding: 5px;
background-color: #dddddd;
}
</style>
</head>
<body>
<table>
<tr>
<td style = "width: 160px; text-align: center">
6 Dicembre 2005
Stefano Clemente
93
Esempio 9: includeDirective.jsp
<img src = "images/logotiny.png"
width = "140" height = "93"
alt = "Deitel & Associates, Inc. Logo" />
</td>
<td>
<%-- include banner.html in this JSP --%>
<%@ include file = "banner.html" %>
</td>
</tr>
<tr>
<td style = "width: 160px">
<%-- include toc.html in this JSP --%>
<%@ include file = "toc.html" %>
</td>
<td style = "vertical-align: top">
<%-- include clock2.jsp in this JSP --%>
<%@ include file = "clock2.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 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
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,
java, javax, 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: 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
public int doStartTag() throws JspException
{
// attempt tag processing
try {
// obtain JspWriter to output content
JspWriter out = pageContext.getOut();
}
// output content
out.print( "Welcome to JSP Tag Libraries!" );
// rethrow IOException to JSP container as JspException
catch( IOException ioException ) {
throw new JspException( ioException.getMessage() );
}
}
}
return SKIP_BODY;
6 Dicembre 2005
// ignore the tag's body
Stefano Clemente
99
Esempio 10 – Passo 2 implementazione
custom tag: advjhtp1-taglib.tld
<?xml version = "1.0"?>
<!DOCTYPE taglib PUBLIC
"-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN"
"http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">
<!-- a tag library descriptor -->
<taglib>
<tlibversion>1.0</tlibversion>
<jspversion>1.1</jspversion>
<shortname>advjhtp1</shortname>
<info>
A simple tab library for the examples
</info>
<!-- A simple tag that outputs content -->
<tag>
<name>welcome</name>
<tagclass>
com.deitel.advjhtp1.jsp.taglibrary.WelcomeTagHandler
</tagclass>
<bodycontent>empty</bodycontent>
<info>
Inserts content welcoming user to tag libraries
</info>
</tag>
……… spazio per altri tag ………
</taglib>
6 Dicembre 2005
Stefano Clemente
100
Esempio 10: customTagWelcome.jsp
<?xml version = "1.0"?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!-- Fig. 10.30: customTagWelcome.jsp
-->
<!-- JSP that uses a custom tag to output content. -->
<!-- taglib directive -->
<%@ taglib uri = "advjhtp1-taglib.tld" prefix = "advjhtp1" %>
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Simple Custom Tag Example</title>
</head>
<body>
<p>The following text demonstrates a custom tag:</p>
<h1>
<advjhtp1:welcome />
</h1>
</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:
customTagAttribute.jsp
<?xml version = "1.0"?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!-- Fig. 10.x: customTagAttribute.jsp
-->
<!-- JSP that uses a custom tag to output content. -->
<%-- taglib directive --%>
<%@ taglib uri = "advjhtp1-taglib.tld" prefix = "advjhtp1" %>
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Specifying Custom Tag Attributes</title>
</head>
<body>
<p>Demonstrating an attribute with a string value</p>
<h1>
<advjhtp1:welcome2 firstName = "Paul" />
</h1>
<p>Demonstrating an attribute with an expression value</p>
<h1>
<%-- scriptlet to obtain "name" request parameter --%>
<%
String name = request.getParameter( "name" );
%>
<advjhtp1:welcome2 firstName = "<%= name %>" />
</h1>
</body>
</html>
6 Dicembre 2005
Stefano Clemente
106
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 = "";
// Method called to begin tag processing
public int doStartTag() throws JspException
{
// attempt tag processing
try {
// obtain JspWriter to output content
6 Dicembre 2005
Stefano Clemente
107
Esempio 11: Welcome2TagHandler.java
JspWriter out = pageContext.getOut();
}
// output content
out.print( "Hello " + firstName +
", <br />Welcome to JSP Tag Libraries!" );
// rethrow IOException to JSP container as JspException
catch( IOException ioException ) {
throw new JspException( ioException.getMessage() );
}
}
}
return SKIP_BODY;
// ignore the tag's body
// set firstName attribute to the users first name
public void setFirstName( String username )
{
firstName = username;
}
6 Dicembre 2005
Stefano Clemente
108
Esempio 11: advjhtp1-taglib.tld
………………
<!-- A tag with an attribute -->
<tag>
<name>welcome2</name>
<tagclass>
com.deitel.advjhtp1.jsp.taglibrary.Welcome2TagHandler
</tagclass>
<bodycontent>empty</bodycontent>
<info>
Inserts content welcoming user to tag libraries. Uses
attribute "name" to insert the user's name.
</info>
<attribute>
<name>firstName</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
………………
6 Dicembre 2005
Stefano Clemente
109
Esempio 11: advjhtp1-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) o
opzionale (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)
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: customTagBody.jsp
<?xml version = "1.0"?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!-- customTagBody.jsp -->
<%-- taglib directive --%>
<%@ taglib uri = "advjhtp1-taglib.tld" prefix = "advjhtp1" %>
<html xmlns = "http://www.w3.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: .9em;
border: 3px groove;
padding: 5px;
background-color: #dddddd
}
</style>
</head>
6 Dicembre 2005
Stefano Clemente
114
Esempio 12: customTagBody.jsp
<body>
<p style = "font-size: 2em">Guest List</p>
<table>
<thead>
<th style = "width: 100px">Last name</th>
<th style = "width: 100px">First name</th>
<th style = "width: 200px">Email</th>
</thead>
<%-- guestlist custom tag --%>
<advjhtp1:guestlist>
<tr>
<td><%= lastName %></td>
<td><%= firstName %></td>
<td>
<a href = "mailto:<%= email %>">
<%= email %></a>
</td>
</tr>
</advjhtp1:guestlist>
</table>
</body>
</html>
6 Dicembre 2005
Stefano Clemente
115
Esempio 12: customTagBody.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 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
6 Dicembre 2005
Stefano Clemente
116
Esempio 12:
GuestBookTag.java
• Il gestore del tag istanzia GuestDataBean per
l’accesso al DB
• GuestBookTag estende la classe
BodyTagSupport che contiene i metodi
dell’interfaccia BodyTag
− doInitBody
• richiamato una sola volta dopo doStartTag e prima di
doAfterBody
• se doStartTag restituisce Tag.SKIP_BODY, non viene
richiamato
− doAfterBody
• 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: 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 lastName;
private String email;
private GuestDataBean guestData;
private GuestBean guest;
6 Dicembre 2005
Stefano Clemente
118
Esempio 12: GuestBookTag.java
private Iterator iterator;
// Method called to begin tag processing
public int doStartTag() throws JspException
{
// attempt tag processing
try {
guestData = new GuestDataBean();
List list = guestData.getGuestList();
iterator = list.iterator();
if ( iterator.hasNext() ) {
processNextGuest();
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: GuestBookTag.java
}
}
exception.printStackTrace();
return SKIP_BODY;
// ignore the tag's body
// process body and determine if body processing
// should continue
public int doAfterBody()
{
// attempt to output body data
try {
bodyContent.writeOut( getPreviousOut() );
}
// if exception occurs, terminate body processing
catch ( IOException ioException ) {
ioException.printStackTrace();
return SKIP_BODY; // terminate body processing
}
bodyContent.clearBody();
if ( iterator.hasNext() ) {
6 Dicembre 2005
Stefano Clemente
120
Esempio 12: GuestBookTag.java
processNextGuest();
return EVAL_BODY_TAG;
}
}
else
return SKIP_BODY;
// continue body processing
// terminate body processing
// obtains the next GuestBean and extracts its data
private void processNextGuest()
{
// get next guest
guest = ( GuestBean ) iterator.next();
pageContext.setAttribute(
"firstName", guest.getFirstName() );
pageContext.setAttribute(
"lastName", guest.getLastName() );
}
}
pageContext.setAttribute(
"email", guest.getEmail() );
6 Dicembre 2005
Stefano Clemente
121
Esempio 12:
GuestBookTagExtraInfo.java
• processNextGuest 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
− non può creare le variabili nel PageContext 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 ExtraInfo alla fine
− GuestBookTagExtraInfo.class
6 Dicembre 2005
Stefano Clemente
122
Esempio 12:
GuestBookTagExtraInfo.java
• ExtraInfo estende la classe TagExtraInfo
del package javax.servlet.jsp.tagext
• Il container usa le informazioni specificate da
una sottoclasse di TagExtraInfo per
determinare le variabili da creare
• Per specificare le variabili bisogna definire il
metodo getVariableInfo in override al
metodo ereditato dalla classe
− 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
6 Dicembre 2005
Stefano Clemente
123
Esempio 12:
GuestBookTagExtraInfo.java
• Il costruttore VariableInfo 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:
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
// GuestBookTag creates for use in a JSP
public VariableInfo [] getVariableInfo( TagData tagData )
{
VariableInfo firstName = new VariableInfo( "firstName",
"String", true, VariableInfo.NESTED );
VariableInfo lastName = new VariableInfo( "lastName",
"String", true, VariableInfo.NESTED );
VariableInfo email = new VariableInfo( "email",
"String", true, VariableInfo.NESTED );
VariableInfo varableInfo [] =
{ firstName, lastName, email };
}
}
return varableInfo;
6 Dicembre 2005
Stefano Clemente
125
Esempio 12: advjhtp1-taglib.tld
………………
<!-- A tag that iterates over an ArrayList of GuestBean -->
<!-- objects, so they can be output in a JSP
-->
<tag>
<name>guestlist</name>
<tagclass>
com.deitel.advjhtp1.jsp.taglibrary.GuestBookTag
</tagclass>
<teiclass>
com.deitel.advjhtp1.jsp.taglibrary.GuestBookTagExtraInfo
</teiclass>
<bodycontent>JSP</bodycontent>
<info>
Iterates over a list of GuestBean 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 JavaBeans
6 Dicembre 2005
Stefano Clemente
129