jsp tag library
DESCRIPTION
Librerie di tag per JSPTRANSCRIPT
![Page 1: JSP Tag Library](https://reader036.vdocumenti.com/reader036/viewer/2022062307/55824c23d8b42a213a8b509c/html5/thumbnails/1.jpg)
Jacopo [email protected]
![Page 2: JSP Tag Library](https://reader036.vdocumenti.com/reader036/viewer/2022062307/55824c23d8b42a213a8b509c/html5/thumbnails/2.jpg)
Scopo della presentazioneIntrodurre il concetto di tag personalizzato;Creare una prima serie di tag in Tomcat;Utilizzare Eclipse per fare il debug
dell’applicazione;Creare tag personalizzati connessi con un
database tramite JNDI.
![Page 3: JSP Tag Library](https://reader036.vdocumenti.com/reader036/viewer/2022062307/55824c23d8b42a213a8b509c/html5/thumbnails/3.jpg)
Tag personalizzatoUn tag personalizzato è un sistema formato da1. Una classe java che estenda una tra le seguenti classi:
javax.servlet.jsp.tagext.TagSupport;javax.servlet.jsp.tagext.BodyTagSupport;
o che implementi l’interfaccia javax.servlet.jsp.tagext.Tag;
2. Un file XML descrittore dell’utilizzo di questa classe Java;3. Una pagina Jsp che contenga un riferimento alla classe.
![Page 4: JSP Tag Library](https://reader036.vdocumenti.com/reader036/viewer/2022062307/55824c23d8b42a213a8b509c/html5/thumbnails/4.jpg)
VantaggiPermettono di semplificare la scrittura del
codice JSPVengono inserite nelle pagine JSP con una
sintassi simile all’HTMLForniscono un metodo per costruire del
codice riutilizzabile (anche tra più progetti)Ne esistono svariate librerie free in rete
![Page 5: JSP Tag Library](https://reader036.vdocumenti.com/reader036/viewer/2022062307/55824c23d8b42a213a8b509c/html5/thumbnails/5.jpg)
SvantaggiE’ NECESSARIO stabilire a priori di quali tag
necessita un progetto (pena la troppa astrazione dello stesso)
Sono difficili da scrivere perchè:Un programmatore sarà sempre portato a
scrivere “un po’ di codice per migliorare la classe”
Un NON programmatore non vorrà mai utilizzare “qualcosa che non sa da dove arrivi”
![Page 6: JSP Tag Library](https://reader036.vdocumenti.com/reader036/viewer/2022062307/55824c23d8b42a213a8b509c/html5/thumbnails/6.jpg)
La classe del Tag personalizzatoE’ un frammento di codice Java inseribile in una pagina Jsp tramite del codice pseudo-HTML;
Deve contenere alcuni metodi particolari che ne controllino il flusso di esecuzione,
Ci sono due tipi di classi di tag: i gestori di tag con corpo e i gestori di tag senza corpo
Sono conformi allo standars JavaBean POJO (Plain Old Java Object):
Dati privati Metodi set e get pubblici per l’accesso ai dati
![Page 7: JSP Tag Library](https://reader036.vdocumenti.com/reader036/viewer/2022062307/55824c23d8b42a213a8b509c/html5/thumbnails/7.jpg)
Tag senza corpo (I) Sono tag HTML paragonabili ai tag HTML:
<img />, <br />, <hr />che non contengono testo apertura e chiusura. Possono gestire attributi dichiarativi, ad es:
<colore:sfondo colore=“RED” />
Nome del tag
Attributo dichiarativo
![Page 8: JSP Tag Library](https://reader036.vdocumenti.com/reader036/viewer/2022062307/55824c23d8b42a213a8b509c/html5/thumbnails/8.jpg)
Tag senza corpo (II)Estendono la classe TagSupport, che contiene i seguenti metodi principali (dalle specifiche J2EE):int doAfterBody() Default processing for a body int doEndTag() Default processing of the end tag returning EVAL_PAGE. int doStartTag() Default processing of the start tag, returning SKIP_BODY. java.lang.Object getValue(java.lang.String k) Get a the value associated with a key. java.util.Enumeration getValues() Enumerate the values kept by this tag handler. void setValue(java.lang.String k, java.lang.Object o) Associate a value with a String key.
![Page 9: JSP Tag Library](https://reader036.vdocumenti.com/reader036/viewer/2022062307/55824c23d8b42a213a8b509c/html5/thumbnails/9.jpg)
Metodi da implementarePer personalizzare la nostra classe è possibile implementare uno dei metodi visti, sapendo che:int doAfterBody()
È il metodo eseguito dopo la lettura del corpo del tag (tutto deriva comunque dall’interfaccia
Tag !!!). int doEndTag()
È il metodo eseguito al termine degli altri metodi e, generalmente, ritorna il valore int EVAL_PAGE. int doStartTag()
È il metodo eseguito prima degli altri metodi e ritorna il valore int SKIP_BODY.
In caso di tag senza corpo questo è, generalmente, il metodo principale da implementare.
![Page 10: JSP Tag Library](https://reader036.vdocumenti.com/reader036/viewer/2022062307/55824c23d8b42a213a8b509c/html5/thumbnails/10.jpg)
Esempio di classe per tag senza corpoEsempio di classe TagSupport:package taglib;
import javax.servlet.jsp.JspException;import javax.servlet.jsp.JspTagException;import javax.servlet.jsp.tagext.TagSupport;
public class DateTag extends TagSupport {public int doStartTag() throws JspException {
try {pageContext.getOut().print(new java.util.Date());
} catch (Exception ex) {throw new JspTagException("DateTag: " +
ex.getMessage());}return SKIP_BODY;
}public int doEndTag() {
return EVAL_PAGE;}
}
![Page 11: JSP Tag Library](https://reader036.vdocumenti.com/reader036/viewer/2022062307/55824c23d8b42a213a8b509c/html5/thumbnails/11.jpg)
Attributi dichiarativiGli attributi vengono gestiti tramite i metodi setValue e getValue della classe Tag di implementazione tramite i metodi visti in precedenza:
java.lang.Object getValue(java.lang.String k) Get a the value associated with a key. void setValue(java.lang.String k, java.lang.Object o) Associate a value with a String key.java.util.Enumeration getValues() Enumerate the values kept by this tag handler.
![Page 12: JSP Tag Library](https://reader036.vdocumenti.com/reader036/viewer/2022062307/55824c23d8b42a213a8b509c/html5/thumbnails/12.jpg)
Attributi dichiarativiPer ogni attributo, così come per le specifiche di JavaBean, devono esistere un metodo set per recuperare il valore del tag dalla pagina JSP e un metodo get se necessario.I metodi get e set devono seguire il seguente formato di esempio:T attr;T getAttr();void setAttr (T attr);
![Page 13: JSP Tag Library](https://reader036.vdocumenti.com/reader036/viewer/2022062307/55824c23d8b42a213a8b509c/html5/thumbnails/13.jpg)
Esempio di recupero attributipackage taglib;
import java.text.SimpleDateFormat;
import javax.servlet.jsp.JspException;import javax.servlet.jsp.JspTagException;import javax.servlet.jsp.tagext.TagSupport;
public class DataFormattataTag extends TagSupport {private String formato;public String getFormato() {
return formato;}
![Page 14: JSP Tag Library](https://reader036.vdocumenti.com/reader036/viewer/2022062307/55824c23d8b42a213a8b509c/html5/thumbnails/14.jpg)
Esempio di recupero attributipublic void setFormato(String formato) {
this.formato = formato;}public int doStartTag() throws JspException {
try {SimpleDateFormat formatter = new
SimpleDateFormat(formato);pageContext.getOut().print(formatter.format(new
java.util.Date()));} catch (Exception ex) {
throw new JspTagException("DateTag: " + ex.getMessage());}return SKIP_BODY;
}public int doEndTag() {
return EVAL_PAGE;}}
![Page 15: JSP Tag Library](https://reader036.vdocumenti.com/reader036/viewer/2022062307/55824c23d8b42a213a8b509c/html5/thumbnails/15.jpg)
Taglib descriptorE’ un file xml contenente la descrizione di
utilizzo della classe tag avente estensione .tld;
Segue le regole del DTD:http://
java.sun.com/dtd/web-jsptaglibrary_1_2.dtd Si trova nella cartella WEB-INF
dell’applicazione Web;Definisce il comportamento di più tag, per
questo di chiama descrittore di libreria.
![Page 16: JSP Tag Library](https://reader036.vdocumenti.com/reader036/viewer/2022062307/55824c23d8b42a213a8b509c/html5/thumbnails/16.jpg)
Principali tag XML nel file taglib: root<taglib>: è la root del documento<tlib-version>: la versione delle specifiche
taglib utilizzata<jsp-version>: la versione delle specifiche
jsp utilizzata<short-name>: un nome descrittivo della
libreria<tag>: inizia la descrizione del
comportamento di una classe di tag personalizzata
![Page 17: JSP Tag Library](https://reader036.vdocumenti.com/reader036/viewer/2022062307/55824c23d8b42a213a8b509c/html5/thumbnails/17.jpg)
Principali tag XML nel file taglib: <tag><name>: il nome del tag da utilizzare nella jsp
<tag-class>: la classe che implementa questo tag
<attribute>: descrizione di un attributo del tag che potrebbe essere presente nella dichiarazione nella pagina jsp
![Page 18: JSP Tag Library](https://reader036.vdocumenti.com/reader036/viewer/2022062307/55824c23d8b42a213a8b509c/html5/thumbnails/18.jpg)
Principali tag XML nel file taglib: <attribute><name>: il nome dell’attributo. Deve
essere uguale nella dichiarazione in JSP e nella classe implementativa.
<required>: specifica se l’attributo è obbligatorio o meno
<rtexprvalue>: specifica se l’attributo può derivare da un’espressione. In caso questo dato fosse true, l’espressione verrebbe calcolata prima di passarne il valore al metodo set della classe.
![Page 19: JSP Tag Library](https://reader036.vdocumenti.com/reader036/viewer/2022062307/55824c23d8b42a213a8b509c/html5/thumbnails/19.jpg)
Descrittore di tag: esempio<?xml version="1.0" encoding="ISO-8859-1" ?><!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN" "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd"><taglib> <tlib-version>1.0</tlib-version> <jsp-version>1.2</jsp-version> <short-name>TagLib001</short-name> <tag> <name>data</name> <tag-class>taglib.DateTag</tag-class> </tag> <tag> <name>dataFormattata</name> <tag-class>taglib.DataFormattataTag</tag-class> <attribute> <name>formato</name> <required>true</required> <rtexprvalue>true</rtexprvalue> </attribute> </tag> </taglib>
![Page 20: JSP Tag Library](https://reader036.vdocumenti.com/reader036/viewer/2022062307/55824c23d8b42a213a8b509c/html5/thumbnails/20.jpg)
Utilizzo dei tag nelle JSP
![Page 21: JSP Tag Library](https://reader036.vdocumenti.com/reader036/viewer/2022062307/55824c23d8b42a213a8b509c/html5/thumbnails/21.jpg)
Esempio di JSP con tag personalizzati (I)
<%@ taglib uri="/WEB-INF/taglib001.tld" prefix="t1" %>
<html>
<head><title>Prima Taglib</title></head>
<body>
<t1:data />
</body>
</html>
![Page 22: JSP Tag Library](https://reader036.vdocumenti.com/reader036/viewer/2022062307/55824c23d8b42a213a8b509c/html5/thumbnails/22.jpg)
Esempio di JSP con tag personalizzati (II)<%@ taglib uri="/WEB-INF/taglib001.tld" prefix="t1" %><html><head><title>Prima Taglib</title></head><body><% if(request.getParameter("formato")==null) { %><form action="<%= request.getRequestURI() %>" method="POST">
Formato: <input type="text" name="formato" /><br /><input type="submit" value="Vedi" /></form><% } else { %><t1:dataFormattata formato="dd/MM/yyyy“ />
<% } %></body></html>
![Page 23: JSP Tag Library](https://reader036.vdocumenti.com/reader036/viewer/2022062307/55824c23d8b42a213a8b509c/html5/thumbnails/23.jpg)
Tag con corpo
Rispetto ai tag senza corpo, hanno la possibilità di gestire il testo tra l’apertura e la chiusura del tag
Estendono la classe BodyTagSupport, che a sua volta estende TagSupport
Possono anch’essi gestire attributi dichiarativi nella stessa identica maniera dei tag senza corpo
Poichè le specifiche XHTML limitano il numero di caratteri inseribili in un attributo, è necessario ricorrere a questi tipi di tag per gestire alcuni processi
![Page 24: JSP Tag Library](https://reader036.vdocumenti.com/reader036/viewer/2022062307/55824c23d8b42a213a8b509c/html5/thumbnails/24.jpg)
Altri metodi da implementareLa classe BodyTagSupport possiede questi particolari metodi, oltre a quelli della classe TagSupport che estende:void doInitBody()
Prepare for evaluation before the first body evaluation.BodyContent getBodyContent()
Get current bodyContent. JspWriter getPreviousOut() Get surrounding out JspWriter. void setBodyContent(BodyContent b)
Prepare for evaluation of the body.
![Page 25: JSP Tag Library](https://reader036.vdocumenti.com/reader036/viewer/2022062307/55824c23d8b42a213a8b509c/html5/thumbnails/25.jpg)
Esempio di tag con corpopackage taglib;
import java.io.IOException;
import javax.servlet.jsp.JspTagException;import javax.servlet.jsp.tagext.BodyContent;import javax.servlet.jsp.tagext.BodyTagSupport;
public class BodyTag extends BodyTagSupport {public int doAfterBody() throws JspTagException {
BodyContent bc = getBodyContent();String text = bc.getString();try {
bodyContent.clearBody();bodyContent.println("Corpo: " + text);bodyContent.writeOut(bodyContent.getEnclosingWriter());
} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();
}return SKIP_BODY;
}}
![Page 26: JSP Tag Library](https://reader036.vdocumenti.com/reader036/viewer/2022062307/55824c23d8b42a213a8b509c/html5/thumbnails/26.jpg)
Descrittore del tag con corpo