ºÝºÝߣ

ºÝºÝߣShare a Scribd company logo
Jacopo Giudici [email_address]
Scopo della presentazione Introdurre 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.
Tag personalizzato Un tag personalizzato ¨¨ un  sistema  formato da 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; Un file XML descrittore dell¡¯utilizzo di questa classe Java; Una pagina Jsp che contenga un riferimento alla classe.
Vantaggi Permettono di semplificare la scrittura del codice JSP Vengono inserite nelle pagine JSP con una sintassi simile all¡¯HTML Forniscono un metodo per costruire del codice riutilizzabile (anche tra pi¨´ progetti) Ne esistono svariate librerie free in rete
Svantaggi E¡¯  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¡±
La classe del Tag personalizzato E¡¯ 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
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
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.
Metodi da implementare Per 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.
Esempio di classe per tag senza corpo Esempio 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( &quot;DateTag: &quot;  +  ex.getMessage()); } return  SKIP_BODY; } public   int  doEndTag() { return  EVAL_PAGE; } }
Attributi dichiarativi Gli 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.
Attributi dichiarativi Per 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);
Esempio di recupero attributi package  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 ; }
Esempio di recupero attributi public   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( &quot;DateTag: &quot;  + ex.getMessage()); } return  SKIP_BODY; } public   int  doEndTag() { return  EVAL_PAGE; } }
Taglib descriptor E¡¯ 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.
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
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
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.
Descrittore di tag: esempio <? xml  version = &quot;1.0&quot;  encoding = &quot;ISO-8859-1&quot;  ?> <! DOCTYPE  taglib PUBLIC  &quot;-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN&quot; &quot;http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd&quot; > < 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 >
Utilizzo dei tag nelle JSP
Esempio di JSP con tag personalizzati (I) <%@  taglib  uri = &quot;/WEB-INF/taglib001.tld&quot;  prefix = &quot;t1&quot;  %> < html > < head >< title > Prima Taglib </ title ></ head > < body > < t1:data  /> </ body > </ html >
Esempio di JSP con tag personalizzati (II) <%@  taglib  uri = &quot;/WEB-INF/taglib001.tld&quot;  prefix = &quot;t1&quot;  %> < html > < head >< title > Prima Taglib </ title ></ head > < body > <%   if (request.getParameter( &quot;formato&quot; )== null ) {  %> < form  action =&quot; <%=  request.getRequestURI()  %>&quot;   method = &quot;POST&quot; > Formato:  < input  type = &quot;text&quot;  name = &quot;formato&quot;  />< br  /> < input  type = &quot;submit&quot;  value = &quot;Vedi&quot;  /> </ form > <%  }  else  {  %> < t1:dataFormattata  formato = &quot;dd/MM/yyyy¡°  /> <%  }  %> </ body > </ html >
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
Altri metodi da implementare La 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.
Esempio di tag con corpo package 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(&quot;Corpo: &quot; + text); bodyContent.writeOut(bodyContent.getEnclosingWriter()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return SKIP_BODY; } }
Descrittore del tag con corpo

More Related Content

Viewers also liked (20)

I Like Shiny Things
I Like Shiny ThingsI Like Shiny Things
I Like Shiny Things
Dino Baskovic
?
TMA Presentation
TMA PresentationTMA Presentation
TMA Presentation
Henry Schneider
?
Feb 18 what we learned kcic
Feb 18  what we learned kcic Feb 18  what we learned kcic
Feb 18 what we learned kcic
Hack the Hood
?
02 - Le R?le des Grappes dans la Strat¨¦gie de Sp¨¦cialisation Intelligente
02 - Le R?le des Grappes dans la Strat¨¦gie de Sp¨¦cialisation Intelligente02 - Le R?le des Grappes dans la Strat¨¦gie de Sp¨¦cialisation Intelligente
02 - Le R?le des Grappes dans la Strat¨¦gie de Sp¨¦cialisation Intelligente
Mohamed Larbi BEN YOUNES
?
³§´Ç´Ú³Ù³¢²¹²â±ð°ù¤Çʼ¤á¤ë¥Ç¥¸¥¿¥ë¥Þ©`¥±¥Æ¥£¥ó¥°
³§´Ç´Ú³Ù³¢²¹²â±ð°ù¤Çʼ¤á¤ë¥Ç¥¸¥¿¥ë¥Þ©`¥±¥Æ¥£¥ó¥°³§´Ç´Ú³Ù³¢²¹²â±ð°ù¤Çʼ¤á¤ë¥Ç¥¸¥¿¥ë¥Þ©`¥±¥Æ¥£¥ó¥°
³§´Ç´Ú³Ù³¢²¹²â±ð°ù¤Çʼ¤á¤ë¥Ç¥¸¥¿¥ë¥Þ©`¥±¥Æ¥£¥ó¥°
Kohei Nishikawa
?
Ppt may october to bulgaria
Ppt may october to bulgariaPpt may october to bulgaria
Ppt may october to bulgaria
Rositsa Dimova
?
Content Repository, Versioning and Workspaces in TYPO3 Phoenix
Content Repository, Versioning and Workspaces in TYPO3 PhoenixContent Repository, Versioning and Workspaces in TYPO3 Phoenix
Content Repository, Versioning and Workspaces in TYPO3 Phoenix
Karsten Dambekalns
?
That Little Something That Doesn¡¯t Quite Fit In: Intra-group Identity Tension...
That Little Something That Doesn¡¯t Quite Fit In: Intra-group Identity Tension...That Little Something That Doesn¡¯t Quite Fit In: Intra-group Identity Tension...
That Little Something That Doesn¡¯t Quite Fit In: Intra-group Identity Tension...
Antia G. Ben
?
The Presence of Multiculturalism in General Music Textbooks: An Exploratory S...
The Presence of Multiculturalism in General Music Textbooks: An Exploratory S...The Presence of Multiculturalism in General Music Textbooks: An Exploratory S...
The Presence of Multiculturalism in General Music Textbooks: An Exploratory S...
Antia G. Ben
?
Task 1
Task 1Task 1
Task 1
Rositsa Dimova
?
SharePoint Online - What is an external user
SharePoint Online - What is an external userSharePoint Online - What is an external user
SharePoint Online - What is an external user
Marwan Tarek
?
How to start an online business:7 stories of success
How to start an online business:7 stories of successHow to start an online business:7 stories of success
How to start an online business:7 stories of success
E-Web Marketing
?
To italy by plane
To italy by planeTo italy by plane
To italy by plane
Rositsa Dimova
?
Mls Preso March 1 2010
Mls Preso March 1 2010Mls Preso March 1 2010
Mls Preso March 1 2010
Hack the Hood
?
An Exploratory Study of the Motivations and Satisfactions on Mobile Web Browsing
An Exploratory Study of the Motivations and Satisfactions on Mobile Web BrowsingAn Exploratory Study of the Motivations and Satisfactions on Mobile Web Browsing
An Exploratory Study of the Motivations and Satisfactions on Mobile Web Browsing
Ruby Kuo
?
Project execution for paranoids
Project execution for paranoidsProject execution for paranoids
Project execution for paranoids
Hack the Hood
?
Melanie duncan checklist-pin worthytutorials-pinterest
Melanie duncan checklist-pin worthytutorials-pinterestMelanie duncan checklist-pin worthytutorials-pinterest
Melanie duncan checklist-pin worthytutorials-pinterest
kovaudio
?
I Jet Exec Sum
I  Jet Exec SumI  Jet Exec Sum
I Jet Exec Sum
Alexey Kostarev
?
The Augmented Reality industry in 15 min.
The Augmented Reality industry in 15 min.The Augmented Reality industry in 15 min.
The Augmented Reality industry in 15 min.
wimvermeulen
?
Feb 18 what we learned kcic
Feb 18  what we learned kcic Feb 18  what we learned kcic
Feb 18 what we learned kcic
Hack the Hood
?
02 - Le R?le des Grappes dans la Strat¨¦gie de Sp¨¦cialisation Intelligente
02 - Le R?le des Grappes dans la Strat¨¦gie de Sp¨¦cialisation Intelligente02 - Le R?le des Grappes dans la Strat¨¦gie de Sp¨¦cialisation Intelligente
02 - Le R?le des Grappes dans la Strat¨¦gie de Sp¨¦cialisation Intelligente
Mohamed Larbi BEN YOUNES
?
³§´Ç´Ú³Ù³¢²¹²â±ð°ù¤Çʼ¤á¤ë¥Ç¥¸¥¿¥ë¥Þ©`¥±¥Æ¥£¥ó¥°
³§´Ç´Ú³Ù³¢²¹²â±ð°ù¤Çʼ¤á¤ë¥Ç¥¸¥¿¥ë¥Þ©`¥±¥Æ¥£¥ó¥°³§´Ç´Ú³Ù³¢²¹²â±ð°ù¤Çʼ¤á¤ë¥Ç¥¸¥¿¥ë¥Þ©`¥±¥Æ¥£¥ó¥°
³§´Ç´Ú³Ù³¢²¹²â±ð°ù¤Çʼ¤á¤ë¥Ç¥¸¥¿¥ë¥Þ©`¥±¥Æ¥£¥ó¥°
Kohei Nishikawa
?
Ppt may october to bulgaria
Ppt may october to bulgariaPpt may october to bulgaria
Ppt may october to bulgaria
Rositsa Dimova
?
Content Repository, Versioning and Workspaces in TYPO3 Phoenix
Content Repository, Versioning and Workspaces in TYPO3 PhoenixContent Repository, Versioning and Workspaces in TYPO3 Phoenix
Content Repository, Versioning and Workspaces in TYPO3 Phoenix
Karsten Dambekalns
?
That Little Something That Doesn¡¯t Quite Fit In: Intra-group Identity Tension...
That Little Something That Doesn¡¯t Quite Fit In: Intra-group Identity Tension...That Little Something That Doesn¡¯t Quite Fit In: Intra-group Identity Tension...
That Little Something That Doesn¡¯t Quite Fit In: Intra-group Identity Tension...
Antia G. Ben
?
The Presence of Multiculturalism in General Music Textbooks: An Exploratory S...
The Presence of Multiculturalism in General Music Textbooks: An Exploratory S...The Presence of Multiculturalism in General Music Textbooks: An Exploratory S...
The Presence of Multiculturalism in General Music Textbooks: An Exploratory S...
Antia G. Ben
?
SharePoint Online - What is an external user
SharePoint Online - What is an external userSharePoint Online - What is an external user
SharePoint Online - What is an external user
Marwan Tarek
?
How to start an online business:7 stories of success
How to start an online business:7 stories of successHow to start an online business:7 stories of success
How to start an online business:7 stories of success
E-Web Marketing
?
An Exploratory Study of the Motivations and Satisfactions on Mobile Web Browsing
An Exploratory Study of the Motivations and Satisfactions on Mobile Web BrowsingAn Exploratory Study of the Motivations and Satisfactions on Mobile Web Browsing
An Exploratory Study of the Motivations and Satisfactions on Mobile Web Browsing
Ruby Kuo
?
Project execution for paranoids
Project execution for paranoidsProject execution for paranoids
Project execution for paranoids
Hack the Hood
?
Melanie duncan checklist-pin worthytutorials-pinterest
Melanie duncan checklist-pin worthytutorials-pinterestMelanie duncan checklist-pin worthytutorials-pinterest
Melanie duncan checklist-pin worthytutorials-pinterest
kovaudio
?
The Augmented Reality industry in 15 min.
The Augmented Reality industry in 15 min.The Augmented Reality industry in 15 min.
The Augmented Reality industry in 15 min.
wimvermeulen
?

Similar to JSP Tag Library (20)

Django: utilizzo avanzato e nuove funzionalit¨¤
Django: utilizzo avanzato e nuove funzionalit¨¤Django: utilizzo avanzato e nuove funzionalit¨¤
Django: utilizzo avanzato e nuove funzionalit¨¤
skam
?
Pycon Jungle
Pycon JunglePycon Jungle
Pycon Jungle
guest6b08a5
?
Javaday 2006: Java 5
Javaday 2006: Java 5Javaday 2006: Java 5
Javaday 2006: Java 5
Matteo Baccan
?
Presentazione wicket
Presentazione wicketPresentazione wicket
Presentazione wicket
Andrea Del Bene
?
Java Advanced
Java AdvancedJava Advanced
Java Advanced
Antonio Furone
?
Rich Ajax Web Interfaces in Jquery
Rich Ajax Web Interfaces in JqueryRich Ajax Web Interfaces in Jquery
Rich Ajax Web Interfaces in Jquery
Alberto Buschettu
?
Lezione JSP database Crud
Lezione JSP database CrudLezione JSP database Crud
Lezione JSP database Crud
Silvano Natalizi - ITIS ALESSANDRO VOLTA PERUGIA
?
Js intro
Js introJs intro
Js intro
Daniele Cruciani
?
Oo Javascript
Oo JavascriptOo Javascript
Oo Javascript
maraexception
?
02 Struts Actions3016
02 Struts Actions301602 Struts Actions3016
02 Struts Actions3016
DavideBos
?
02 Struts Actions
02  Struts  Actions02  Struts  Actions
02 Struts Actions
Federico Paparoni
?
02 Struts Actions3016
02 Struts Actions301602 Struts Actions3016
02 Struts Actions3016
DavideBos
?
April 2010 - Seam unifies JEE5
April 2010 - Seam unifies JEE5April 2010 - Seam unifies JEE5
April 2010 - Seam unifies JEE5
JBug Italy
?
Seam unifies Java EE by Massimiliano Ciccazzo
Seam unifies Java EE by Massimiliano CiccazzoSeam unifies Java EE by Massimiliano Ciccazzo
Seam unifies Java EE by Massimiliano Ciccazzo
Java User Group Roma
?
Lezione07
Lezione07Lezione07
Lezione07
Gerardo Zenga
?
jQuery e i suoi plugin
jQuery e i suoi pluginjQuery e i suoi plugin
jQuery e i suoi plugin
Pasquale Puzio
?
Web Performance Optimization
Web Performance OptimizationWeb Performance Optimization
Web Performance Optimization
Alessandro Martin
?

JSP Tag Library

  • 2. Scopo della presentazione Introdurre 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.
  • 3. Tag personalizzato Un tag personalizzato ¨¨ un sistema formato da 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; Un file XML descrittore dell¡¯utilizzo di questa classe Java; Una pagina Jsp che contenga un riferimento alla classe.
  • 4. Vantaggi Permettono di semplificare la scrittura del codice JSP Vengono inserite nelle pagine JSP con una sintassi simile all¡¯HTML Forniscono un metodo per costruire del codice riutilizzabile (anche tra pi¨´ progetti) Ne esistono svariate librerie free in rete
  • 5. Svantaggi E¡¯ 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¡±
  • 6. La classe del Tag personalizzato E¡¯ 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
  • 7. 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
  • 8. 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.
  • 9. Metodi da implementare Per 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.
  • 10. Esempio di classe per tag senza corpo Esempio 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( &quot;DateTag: &quot; + ex.getMessage()); } return SKIP_BODY; } public int doEndTag() { return EVAL_PAGE; } }
  • 11. Attributi dichiarativi Gli 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.
  • 12. Attributi dichiarativi Per 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);
  • 13. Esempio di recupero attributi package 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 ; }
  • 14. Esempio di recupero attributi public 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( &quot;DateTag: &quot; + ex.getMessage()); } return SKIP_BODY; } public int doEndTag() { return EVAL_PAGE; } }
  • 15. Taglib descriptor E¡¯ 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.
  • 16. 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
  • 17. 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
  • 18. 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.
  • 19. Descrittore di tag: esempio <? xml version = &quot;1.0&quot; encoding = &quot;ISO-8859-1&quot; ?> <! DOCTYPE taglib PUBLIC &quot;-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN&quot; &quot;http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd&quot; > < 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 >
  • 20. Utilizzo dei tag nelle JSP
  • 21. Esempio di JSP con tag personalizzati (I) <%@ taglib uri = &quot;/WEB-INF/taglib001.tld&quot; prefix = &quot;t1&quot; %> < html > < head >< title > Prima Taglib </ title ></ head > < body > < t1:data /> </ body > </ html >
  • 22. Esempio di JSP con tag personalizzati (II) <%@ taglib uri = &quot;/WEB-INF/taglib001.tld&quot; prefix = &quot;t1&quot; %> < html > < head >< title > Prima Taglib </ title ></ head > < body > <% if (request.getParameter( &quot;formato&quot; )== null ) { %> < form action =&quot; <%= request.getRequestURI() %>&quot; method = &quot;POST&quot; > Formato: < input type = &quot;text&quot; name = &quot;formato&quot; />< br /> < input type = &quot;submit&quot; value = &quot;Vedi&quot; /> </ form > <% } else { %> < t1:dataFormattata formato = &quot;dd/MM/yyyy¡° /> <% } %> </ body > </ html >
  • 23. 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
  • 24. Altri metodi da implementare La 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.
  • 25. Esempio di tag con corpo package 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(&quot;Corpo: &quot; + text); bodyContent.writeOut(bodyContent.getEnclosingWriter()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return SKIP_BODY; } }
  • 26. Descrittore del tag con corpo