Ce diaporama a bien été signalé.
Le téléchargement de votre SlideShare est en cours. ×

Java EE _ JSTL (1).pdf

Publicité
Publicité
Publicité
Publicité
Publicité
Publicité
Publicité
Publicité
Publicité
Publicité
Publicité
Publicité
Prochain SlideShare
Java EE _ JSP.pdf
Java EE _ JSP.pdf
Chargement dans…3
×

Consultez-les par la suite

1 sur 51 Publicité

Java EE _ JSTL (1).pdf

Télécharger pour lire hors ligne

Java EE _ JSTL (1).pdfJava EE _ JSTL (1).pdfJava EE _ JSTL (1).pdfJava EE _ JSTL (1).pdfJava EE _ JSTL (1).pdfJava EE _ JSTL (1).pdfJava EE _ JSTL (1).pdfJava EE _ JSTL (1).pdfJava EE _ JSTL (1).pdfJava EE _ JSTL (1).pdfJava EE _ JSTL (1).pdfJava EE _ JSTL (1).pdfJava EE _ JSTL (1).pdfJava EE _ JSTL (1).pdfJava EE _ JSTL (1).pdfJava EE _ JSTL (1).pdfJava EE _ JSTL (1).pdfJava EE _ JSTL (1).pdf

Java EE _ JSTL (1).pdfJava EE _ JSTL (1).pdfJava EE _ JSTL (1).pdfJava EE _ JSTL (1).pdfJava EE _ JSTL (1).pdfJava EE _ JSTL (1).pdfJava EE _ JSTL (1).pdfJava EE _ JSTL (1).pdfJava EE _ JSTL (1).pdfJava EE _ JSTL (1).pdfJava EE _ JSTL (1).pdfJava EE _ JSTL (1).pdfJava EE _ JSTL (1).pdfJava EE _ JSTL (1).pdfJava EE _ JSTL (1).pdfJava EE _ JSTL (1).pdfJava EE _ JSTL (1).pdfJava EE _ JSTL (1).pdf

Publicité
Publicité

Plus De Contenu Connexe

Similaire à Java EE _ JSTL (1).pdf (20)

Plus récents (20)

Publicité

Java EE _ JSTL (1).pdf

  1. 1. JSTL – JSP STANDARD TAG LIBRARY 2022/2023 JAKARTA ENTREPRISE EDITION - SELMA BATTI ATTIA 144
  2. 2. Plan • TagLibs • Principe de JSTL • Exemple • JSTL EL • JSTL core et heads • TagLibs personnalisée • Cycle de vie • Syntaxe 2022/2023 JAKARTA ENTREPRISE EDITION - SELMA BATTI ATTIA 145
  3. 3. Les TagLibs • La spécification des JSP prévoit la possibilité de définir ses propres tags XML • Un ensemble de tag est regroupé au sein d’une taglib qui possède URI comme identifiant unique 2022/2023 JAKARTA ENTREPRISE EDITION - SELMA BATTI ATTIA 146
  4. 4. JSP Standard Tag Library • Ensemble de tags pré-programmés permettant d’effectuer les opérations standard • Initiative Apache spécifiée via la JSR052 • Plusieurs parties : ◦ Core (http://java.sun.com/jstl/core) ◦ Internationalisation (http://java.sun.com/jstl/fmt) ◦ XML (http://java.sun.com/jstl/xml) ◦ SQL (http://java.sun.com/jstl/sql) 2022/2023 JAKARTA ENTREPRISE EDITION - SELMA BATTI ATTIA 147
  5. 5. Hello JSTL • Affiche le champs User-Agent des entêtes 2022/2023 JAKARTA ENTREPRISE EDITION - SELMA BATTI ATTIA 148 Ajout des Jars de la JSTL Directive de la taglib core Définie une variable (script) Affiche
  6. 6. Hello JSTL • Affiche la version du browser 2022/2023 JAKARTA ENTREPRISE EDITION - SELMA BATTI ATTIA 149
  7. 7. JSTL Expression Langage • Langage de script à l’intérieur des attributs des tags 2022/2023 JAKARTA ENTREPRISE EDITION - SELMA BATTI ATTIA 150 <%@ taglib prefix="core" uri="http://java.sun.com/jsp/jstl/core" %> <html> <body bgcolor="white"> <core:set var="browser" value="${header['User-Agent']}"/> <core:out value="${browser}"/> </body> </html> <html> <body bgcolor="white"> <%= request.getHeader("User-Agent") %> </body> </html>
  8. 8. Deux taglibs jumelles • 2 langages de script : ◦ RunTime Script: ◦ <%= article.getName() %> ◦ Expression Language Script : ◦ ${article.name} • 2 taglibs : ◦ RT : http://java.sun.com/jstl/core_rt ◦ EL : http://java.sun.com/jstl/core 2022/2023 JAKARTA ENTREPRISE EDITION - SELMA BATTI ATTIA 153
  9. 9. JSTL: core • Déclaration : ◦ core:set, ◦ core:declare, ◦ core:remove • Affichage : ◦ core:out • Condition : ◦ core:if, ◦ core:choose/when/otherwise, ◦ core:catch • Itération : ◦ core:forEach, ◦ core:forTokens 2022/2023 JAKARTA ENTREPRISE EDITION - SELMA BATTI ATTIA 154 Déclare une variable locale Définie une variable scopée Retire une variable scopée Affiche Switch Attrape les exceptions Itère sur une collection ou un tableau Itère sur des portions de String découpée par des délimiteurs
  10. 10. JSTL : core (exemple) • Affiche Rebonjour après reload 2022/2023 JAKARTA ENTREPRISE EDITION - SELMA BATTI ATTIA 155 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html> <body bgcolor="white"> <c:choose> <c:when test="${loggedIn}"> <h1>Rebonjour</h1> </c:when> <c:otherwise> <h1>Bonjour</h1> </c:otherwise> </c:choose> <c:set var="loggedIn" scope="session" value="${true}"/> Please Reload me !! </body> </html>
  11. 11. JSTL : headers • Mélange RT et EL Core taglibs 2022/2023 JAKARTA ENTREPRISE EDITION - SELMA BATTI ATTIA 156 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="crt" uri="http://java.sun.com/jstl/core_rt" %> <html> <body bgcolor="white"> <h1>Headers</h1> <dl> <crt:forEach items="<%= request.getHeaderNames() %>" var="h"> <dt><c:out value="${h}"/></dt> <dd><c:out value="${header[h]}"/></dd> </crt:forEach> </body> </html>
  12. 12. Écrire sa propre Taglib • Écrire le code des tags (implantant Tag, BodyTag) • Définir un Tag Library Descriptor (fichier XML contenant la définition des tags) • Référencer le TLD dans le web.xml • Déclaration par une directive de taglib lors de l’utilisation 2022/2023 JAKARTA ENTREPRISE EDITION - SELMA BATTI ATTIA 157
  13. 13. Exemple HelloTag • Création d’un tag affichant « hello world » 2022/2023 JAKARTA ENTREPRISE EDITION - SELMA BATTI ATTIA 158 <%@ taglib uri="http://www.univ-mlv.fr/taglibs/tagdemo" prefix="tgd" %> <html> <head> <title>Hello World Tag</title> </head> <body bgcolor="white"> <h1><tgd:helloworld/></h1> </body> </html>
  14. 14. Création de la classe • La classe implémente Tag (TagSupport implémente Tag) 2022/2023 JAKARTA ENTREPRISE EDITION - SELMA BATTI ATTIA 159 package fr.umlv.tagdemo; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; public class HelloWorldTag extends TagSupport { public int doStartTag() throws JspException { try { pageContext.getOut().print("Hello World"); } catch (Exception e) { throw new JspTagException(e.getMessage()); } return SKIP_BODY; } public int doEndTag() { return EVAL_PAGE; } } Ne pas évaluer l’intérieur du tag Évalue la suite de la page
  15. 15. Cycle de vie d’un Tag • Initialisation : ◦ setPageContext(), fixe le contexte de page ◦ setParent(), fixe le tag père ◦ set*(value) initialise les attributs • doStartTag() appelée à la balise ouvrante • doEndTag() appelée à la balise fermante • release() libère les ressources 2022/2023 JAKARTA ENTREPRISE EDITION - SELMA BATTI ATTIA 160
  16. 16. Cycle de vie d’un Tag (2) • Valeurs de retour possibles pour : ◦ doStartTag() ◦ EVAL_BODY_INCLUDE le contenu entre les balises est évalué ◦ SKIP_BODY le contenu n’est pas évalué ◦ doEndTag() ◦ EVAL_PAGE continue l’évaluation de la page ◦ SKIP_PAGE stoppe l’évaluation de la page 2022/2023 JAKARTA ENTREPRISE EDITION - SELMA BATTI ATTIA 161
  17. 17. Tag Library Descriptor • Fichier XML de description des tags 2022/2023 JAKARTA ENTREPRISE EDITION - SELMA BATTI ATTIA 162 <?xml version="1.0" encoding="ISO-8859-1" ?> <!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN" "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd"> <taglib> <tlibversion>1.0</tlibversion> <jspversion>1.2</jspversion> <shortname>tgd</shortname> <uri>http://www.univ-mlv.fr/taglibs/tagdemo</uri> <info>Demo Tag Library</info> <tag> <name>helloworld</name> <tagclass>fr.umlv.tagdemo.HelloWorldTag</tagclass> <bodycontent>empty</bodycontent> <info>print helloworld</info> </tag> </taglib> Nom de la classe Nom du tag URI associée à la taglib Le contenu est ignoré doStart() doit renvoyer SKIP_BODY
  18. 18. Déclaration du TLD • Déclaration du fichier de la taglib dans le web.xml 2022/2023 JAKARTA ENTREPRISE EDITION - SELMA BATTI ATTIA 163 <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web- app_4_0.xsd" id="WebApp_ID" version="4.0" > <display-name>ProjetJSTL</display-name> <jsp-config> <taglib> <taglib-uri>http://www.tek-up.tn/newtaglibs/newTagHW</taglib-uri> <taglib-location> /WEB-INF/lib/HWDesc.tld </taglib-location> </taglib> </jsp-config> </web-app>
  19. 19. Fichiers sur le disque • Les différents fichiers sur le disque 2022/2023 JAKARTA ENTREPRISE EDITION - SELMA BATTI ATTIA 164
  20. 20. Tag avec attributs • Lors de l’initialisation d’un tag pour chaque attribut du tag la méthode setAttributeName(String value) est appelée 2022/2023 JAKARTA ENTREPRISE EDITION - SELMA BATTI ATTIA 165 <%@ taglib uri="http://www.univ-mlv.fr/taglibs/tagdemo" prefix="tgd" %> <html> <head> <title>Message Tag</title> </head> <body bgcolor="white"> <tgd:message value="helloworld"/><br> </body> </html>
  21. 21. Tag avec attributs • Appel la méthode setValue("helloworld") 2022/2023 JAKARTA ENTREPRISE EDITION - SELMA BATTI ATTIA 166 public class MessageTag extends TagSupport { public int doStartTag() throws JspException { try { pageContext.getOut().print(value); } catch (Exception e) { throw new JspTagException(e.getMessage()); } return SKIP_BODY; } public int doEndTag() { return EVAL_PAGE; } public void setValue(String value) { this.value=value; } private String value; }
  22. 22. Déclarer les attributs • Les attributs sont déclarés dans le TLD 2022/2023 JAKARTA ENTREPRISE EDITION - SELMA BATTI ATTIA 167 <tag> <name>message</name> <tagclass>fr.umlv.tagdemo.MessageTag</tagclass> <bodycontent>empty</bodycontent> <info>print a message passed as attribute</info> <attribute> <name>value</name> <required>true</required> <rtexprvalue>false</rtexprvalue> </attribute> </tag> Nom de l’attribut Attribut obligatoire ?? La valeur peut être le résultat d’un script
  23. 23. Attribut des Tags & Script • Un attribut peut prendre en paramètre une valeur calculée lors de l’exécution 2022/2023 JAKARTA ENTREPRISE EDITION - SELMA BATTI ATTIA 168 <%@ taglib uri="http://www.univ-mlv.fr/taglibs/tagdemo" prefix="tgd" %> <html> <head> <title>Message Tag</title> </head> <body bgcolor="white"> <tgd:message value="helloworld"/> <br> <tgd:rt-message value="helloworld"/> <br> <tgd:message value="<%= request.getHeader("user-agent") %>"/> <br> <tgd:rt-message value="<%= request.getHeader("user-agent") %>"/> </body> </html> rtexprvalue=false rtexprvalue=true
  24. 24. Attribut des Tags & Script (2) • Si rtexprvalue=false alors pas d’évaluation des expressions à l’exécution 2022/2023 JAKARTA ENTREPRISE EDITION - SELMA BATTI ATTIA 169
  25. 25. Déclaration de variables dans un Tag • Comment déclarer un variable locale ? 2022/2023 JAKARTA ENTREPRISE EDITION - SELMA BATTI ATTIA 170 <%@ taglib uri="http://www.univ-mlv.fr/taglibs/tagdemo" prefix="tgd" %> <html> <head> <title>Declare Tag</title> </head> <body bgcolor="white"> <tgd:declare name="variable" type="java.lang.String" value="toto"/> <%= variable %>.length()= <%= variable.length() %> </body> </html>
  26. 26. Déclaration de variables dans un tag • La valeur est manipuler en utilisant le pageContext 2022/2023 JAKARTA ENTREPRISE EDITION - SELMA BATTI ATTIA 171 public class DeclareTag extends TagSupport { public int doStartTag() throws JspException { return SKIP_BODY; } public int doEndTag() { pageContext.setAttribute(name, transtype(value,type)); return EVAL_PAGE; } private Object transtype( String value, Class type) { return value; } private String name,value; private Class type; public void setType(String className) { try { type=Class.forName(className); } catch (ClassNotFoundException e) { this.type=null; } } public void setName(String name) { this.name=name; } public void setValue(String value) { this.value=value; } }
  27. 27. TagExtraInfo • Permet de définir des variables pendant l’étape de traduction 2022/2023 JAKARTA ENTREPRISE EDITION - SELMA BATTI ATTIA 172 public class DeclareTagExtraInfo extends TagExtraInfo { public VariableInfo[] getVariableInfo(TagData data) { return new VariableInfo[] { new VariableInfo( data.getAttributeString("name"), data.getAttributeString("type"), true, VariableInfo.AT_END) }; } } NESTED : entre les balises ouvrantes et fermantes AT_BEGIN : de la balise ouvrantes à la fin de fichier AT_END : de la balise fermante à la fin de fichier Type de la variable Nom de la variable Info sur le tag Déclaration de la variable
  28. 28. Déclaration du TagExtraInfo • Déclaration dans le fichier TLD 2022/2023 JAKARTA ENTREPRISE EDITION - SELMA BATTI ATTIA 173 <tag> <name>declare</name> <tagclass>fr.umlv.tagdemo.DeclareTag</tagclass> <teiclass>fr.umlv.tagdemo.DeclareTagExtraInfo</teiclass> <bodycontent>empty</bodycontent> <info>declare a variable with page scope</info> <attribute> <name>name</name> <required>true</required> <rtexprvalue>false</rtexprvalue> </attribute> <attribute> <name>value</name> <required>false</required> <rtexprvalue>true</rtexprvalue> </attribute> … </tag>
  29. 29. Traduction d’un Tag • Traduction de la JSP en servlet 2022/2023 JAKARTA ENTREPRISE EDITION - SELMA BATTI ATTIA 174 fr.umlv.tagdemo.DeclareTag _jspx_th_tgd_declare_0 = (fr.umlv.tagdemo.DeclareTag) _jspx_tagPool_tgd_declare_value_type_name.get( fr.umlv.tagdemo.DeclareTag.class); _jspx_th_tgd_declare_0.setPageContext(pageContext); _jspx_th_tgd_declare_0.setParent(null); _jspx_th_tgd_declare_0.setName("variable"); _jspx_th_tgd_declare_0.setType("java.lang.String"); _jspx_th_tgd_declare_0.setValue("toto"); int _jspx_eval_tgd_declare_0 = _jspx_th_tgd_declare_0.doStartTag(); if (_jspx_th_tgd_declare_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) return; _jspx_tagPool_tgd_declare_value_type_name.reuse(_jspx_th_tgd_declare_0); java.lang.String variable = null; variable = (java.lang.String) pageContext.findAttribute("variable"); out.write("rn rn "); out.print( variable ); out.write(".length()= "); out.print( variable.length() );
  30. 30. Évaluation conditionnelle • On veut évaluer le contenu entre les deux balises if si la valeur de l’attribut est vrai 2022/2023 JAKARTA ENTREPRISE EDITION - SELMA BATTI ATTIA 175 <%@ taglib uri="http://www.univ-mlv.fr/taglibs/tagdemo" prefix="tgd" %> <html> <body bgcolor="white"> <tgd:if value="true"> test ok </tgd:if> <tgd:if value="false"> test wrong </tgd:if> </body> </html>
  31. 31. Évaluation conditionnelle • doStartTag() renvoie une valeur différentes 2022/2023 JAKARTA ENTREPRISE EDITION - SELMA BATTI ATTIA 176 public class IfTag extends TagSupport { public int doStartTag() throws JspException { return (condition)?EVAL_BODY_INCLUDE:SKIP_BODY; } public int doEndTag() { return EVAL_PAGE; } public void setValue(String value) { condition=Boolean.valueOf(value). booleanValue(); } private boolean condition; } <tag> <name>if</name> <tagclass>fr.umlv.tagdemo.IfTag</tagclass> <teiclass>fr.umlv.tagdemo.IfTagExtraInfo</teiclass> <bodycontent>JSP</bodycontent> <info>conditional execution</info> <attribute> <name>value</name> <required>true</required> <rtexprvalue>true</rtexprvalue> </attribute> </tag>
  32. 32. Validation des attributs • Assurer à la traduction que le tag if prend bien une valeur booléenne 2022/2023 JAKARTA ENTREPRISE EDITION - SELMA BATTI ATTIA 177 public class IfTagExtraInfo extends TagExtraInfo { public boolean isValid(TagData data) { Object value = data.getAttribute("value"); if (value == TagData.REQUEST_TIME_VALUE) return true; String text=value.toString().toLowerCase(); return text.equals("true") || text.equals("false"); } } Indique une expression calculée à l’exécution Est appelée lors de la traduction pour valider les arguments
  33. 33. Validation des attributs (2) • Permet uniquement de valider les valeurs lors de la traduction 2022/2023 JAKARTA ENTREPRISE EDITION - SELMA BATTI ATTIA 178 <%@ taglib uri="http://www.univ-mlv.fr/taglibs/tagdemo" prefix="tgd" %> <html> <body bgcolor="white"> <tgd:if value="false"> test wrong </tgd:if> <tgd:if value="hello"> test wrong </tgd:if> <% String test="hello"; %> <tgd:if value="<%= test %>"> test ok </tgd:if> </body> </html> Traduction ok Erreur à la traduction Ok, pas d’erreur de traduction
  34. 34. Les BodyTag • Un BodyTag permet : ◦ d’effectuer des itérations sur le contenu ◦ d’effectuer des post-traitement sur le contenu • La valeur renvoyer par doStartTag() permet de choisir 2022/2023 JAKARTA ENTREPRISE EDITION - SELMA BATTI ATTIA 179
  35. 35. Cycle de vie d’un BodyTag (1) • Itérer sur le contenu (body) : ◦ Initialisation (set*) ◦ Si doStartTag() renvoie EVAL_BODY_INCLUDE ◦ doInitBody() ◦ Évalue le contenu du body ◦ Boucle sur le doAfterBody() si EVAL_BODY_AGAIN ◦ doEndTag(); ◦ release(); 2022/2023 JAKARTA ENTREPRISE EDITION - SELMA BATTI ATTIA 180
  36. 36. Cycle de vie d’un BodyTag (2) • Bufferiser le contenu (body) : ◦ Initialisation (set*) ◦ Si doStartTag() renvoie EVAL_BODY_BUFFERED ◦ out = pageContext.pushBody(), setBodyContent(out); ◦ doInitBody() ◦ Évalue le contenu du body ◦ Boucle sur le doAfterBody() si EVAL_BODY_AGAIN ◦ doEndTag(); ◦ pageContext.popBody(); ◦ release(); 2022/2023 JAKARTA ENTREPRISE EDITION - SELMA BATTI ATTIA 181
  37. 37. Tag d’Itération • Pouvoir utiliser un tag pour itérer sur une collection 2022/2023 JAKARTA ENTREPRISE EDITION - SELMA BATTI ATTIA 182 <%@ taglib uri="http://www.univ-mlv.fr/taglibs/tagdemo" prefix="tgd" %> <html> <body bgcolor="white"> <ul> <tgd:iterate collection="<%= request.getHeaderNames() %>"> <li><tgd:item/></li> </tgd:iterate> </ul> </body> </html>
  38. 38. Tag d’Itération (2) • Le TLD et le TagExtraInfo correspondant 2022/2023 JAKARTA ENTREPRISE EDITION - SELMA BATTI ATTIA 183 <tag> <name>iterate</name> <tagclass>fr.umlv.tagdemo.IterateTag</tagclass> <teiclass>fr.umlv.tagdemo.IterateTagExtraInfo</teiclass> <bodycontent>JSP</bodycontent> <info>iterate over a collection</info> <attribute> <name>collection</name> <required>true</required> <rtexprvalue>true</rtexprvalue> </attribute> </tag> <tag> <name>item</name> <tagclass>fr.umlv.tagdemo.ItemTag</tagclass> <bodycontent>empty</bodycontent> <info>print an item</info> </tag> public class IterateTagExtraInfo extends TagExtraInfo { public VariableInfo[] getVariableInfo(TagData data) { return new VariableInfo[] { new VariableInfo( "item", "java.lang.Object", true, VariableInfo.NESTED) }; } } Variable locale au body Nom de la variable Type de la variable Le tag regarde le contenu
  39. 39. Tag d’Itération (3) • Code du tag iterate 2022/2023 JAKARTA ENTREPRISE EDITION - SELMA BATTI ATTIA 184 public class IterateTag extends BodyTagSupport { public int doStartTag() throws JspException { if (!iterator.hasNext()) return SKIP_BODY; pageContext.setAttribute("item", iterator.next()); return EVAL_BODY_INCLUDE; } public int doAfterBody() throws JspException { if (!iterator.hasNext()) return SKIP_BODY; pageContext.setAttribute("item", iterator.next()); return EVAL_BODY_AGAIN; } public void setCollection(Object value) { if (value instanceof Iterator) { iterator=(Iterator)value; } else throw new RuntimeException("bad collection "+value); } private Iterator iterator; } Implémente BodyTag Exécute le contenu du body Ré-exécute le contenu du body
  40. 40. Tag d’Itération (4) • Code du Tag item 2022/2023 JAKARTA ENTREPRISE EDITION - SELMA BATTI ATTIA 185 public class ItemTag extends TagSupport { public int doStartTag() throws JspException { try { pageContext.getOut().print(pageContext.getAttribute("item")); } catch (IOException e) { throw new JspException(e.getMessage()); } return SKIP_BODY; } public int doEndTag() { return EVAL_PAGE; } } <tag> <name>item</name> <tagclass>fr.umlv.tagdemo.ItemTag</tagclass> <bodycontent>empty</bodycontent> <info>print an item</info> </tag> Tag Library Descriptor
  41. 41. Post traitement du contenu • Appliquer une feuille de style à un contenu 2022/2023 JAKARTA ENTREPRISE EDITION - SELMA BATTI ATTIA 186 <%@ taglib uri="http://www.univ-mlv.fr/taglibs/tagdemo" prefix="tgd" %> <html> <head> <title>XSLT Tag</title> </head> <body bgcolor="white"> <tgd:xslt stylesheet="helloworld.xsl"> <helloworld/> </tgd:xslt> </body> </html> <?xml version="1.0" encoding="latin1"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:output method="xml" encoding = "isolatin1" omit-xml-declaration = "yes" indent = "yes"/> <xsl:template match="helloworld"> hello world !! </xsl:template> </xsl:stylesheet>
  42. 42. Post traitement du contenu (2) • EVAL_BODY_BUFFERED permet de bufferiser le contenu 2022/2023 JAKARTA ENTREPRISE EDITION - SELMA BATTI ATTIA 187 public class XSLTag extends BodyTagSupport { public int doStartTag() throws JspException { return EVAL_BODY_BUFFERED; } public int doAfterBody() throws JspException { return SKIP_BODY; } public int doEndTag() throws JspException { Reader reader=getBodyContent().getReader(); try { transformer.transform( new StreamSource(reader), new StreamResult(pageContext.getOut())); } catch (TransformerException e) { throw new JspException(e.getMessage()); } return EVAL_PAGE; } public void setStylesheet(String file) throws TransformerConfigurationException { TransformerFactory factory= TransformerFactory.newInstance(); Templates template=factory.newTemplates( new StreamSource(new File( pageContext.getServletContext(). getRealPath(file)))); transformer=template.newTransformer(); } private Transformer transformer; } Bufferise le contenu Il est interdit d’utiliser out ici
  43. 43. Extensions de JSP 2.0 • Include automatique preclude/coda. • Script à l’intérieur des attributs des beans. • Fragment JSP (sorte de templates, tiles de struts) • Interface SimpleTag pour les Tags 2022/2023 JAKARTA ENTREPRISE EDITION - SELMA BATTI ATTIA 188
  44. 44. Pas de code Java dans les JSP • On mélange l’interface graphique et le code métier • Les erreurs de syntaxes sont détectés lors du déploiement • Le code est dure à lire 2022/2023 JAKARTA ENTREPRISE EDITION - SELMA BATTI ATTIA 189
  45. 45. Exercice • Soit une JSP (sous forme d’un formulaire) qui permet à l’utilisateur de donner : ◦ son nom ; ◦ son prénom ; ◦ les pays qu'il a visités parmi une liste de choix par défaut ; ◦ d'autres pays qu'il a visités, en les séparant par une virgule. • Écrire une page initProcess.jsp qui se charge de traiter les données saisies dans la page contenant ce formulaire. ◦ Utiliser les données saisies par le client dans les champs du formulaire qui sont accessibles dans la JSP à travers les paramètres de requêtes, (l'objet implicite param). 2022/2023 JAKARTA ENTREPRISE EDITION - SELMA BATTI ATTIA 190
  46. 46. Page « initForm.jsp » • <%@ page pageEncoding="UTF-8" %> • <!DOCTYPE html> • <html> • <head> • <meta charset="utf-8" /> • <title> • Initialisation des données • </title> • </head> 2022/2023 JAKARTA ENTREPRISE EDITION - SELMA BATTI ATTIA 191
  47. 47. 2022/2023 JAKARTA ENTREPRISE EDITION - SELMA BATTI ATTIA 192 • <body> • <form method="post" action="initProcess.jsp"> • <p> • <label for="nom">Entrez ici votre nom de famille • :</label><br /> • <input type="text" name="nom" id="nom" tabindex="10" /> • </p> • <p> • <label for="prenom">Entrez ici votre prénom :</label><br /> • <input type="text" name="prenom" id="prenom" tabindex="20" • /> • </p>
  48. 48. 2022/2023 JAKARTA ENTREPRISE EDITION - SELMA BATTI ATTIA 193 • <p> • <label for="pays">Dans quel(s) pays avez-vous déjà voyagé • ?</label><br /> • <select name="pays" id="pays" multiple="multiple" • tabindex="30"> • <option value="France">France</option> • <option value="Espagne">Espagne</option> • <option value="Italie">Italie</option> • <option value="Royaume-uni">Royaume-Uni</option> • <option value="Canada">Canada</option> • <option value="Etats-unis">Etats-Unis</option> • <option value="Chine">Chine</option> • <option value="Japon">Japon</option> • </select> • </p>
  49. 49. 2022/2023 JAKARTA ENTREPRISE EDITION - SELMA BATTI ATTIA 194 • <p> • <label for="autre">Entrez ici les autres pays que vous avez • visités, séparés par une virgule :</label><br /> • <textarea id="autre" name="autre" rows="2" cols="40" • tabindex="40" placeholder="Ex: Norvège, Chili, Nouvelle- • Zélande"></textarea> • </p> • <p> • <input type="submit" value="Valider" /> <input type="reset" • value="Remettre à zéro" /> • </p> • </form> • </body> • </html>
  50. 50. Exercice (Examen 2018/2019) • L’objectif de cet exercice est de réaliser un prototype d’un site web dynamique pour déposer une demande de crédit. • Pour simplifier ce projet : ◦ L’authentification et l’identification ne sont pas traitées. ◦ Un crédit a un type (immobilier, consommation ou projet), un montant (en DT) et une durée de remboursement (en mois) ◦ Un utilisateur est identifié par un nom et un prénom et peut déposer des demandes pour plusieurs crédits. • L’utilisateur de ce site peut consulter une page dont l’URL est « credit » en précisant son nom, son prénom, le type du crédit, son montant et sa durée par les paramètres de l’URL ; une nouvelle demande de crédit pour cet utilisateur est alors enregistrée et l’affichage de toutes les demandes de l’utilisateur sont affichée. L’utilisateur peut aussi consulter la page ayant comme URL « credit » en précisant seulement son nom et prénom pour consulter toutes les demandes de crédit de l’utilisateur. 2022/2023 JAKARTA ENTREPRISE EDITION - SELMA BATTI ATTIA 195
  51. 51. Suite 1. Donner le code java des classes représentant le modèle de ce projet. 2. Donner le code de la JSP qui récupère les informations concernant un utilisateur et affiche ses demandes de crédits tout en respectant le modèle MVC. 3. Donner le code de la servlet correspondante. 4. Donner le code du fichier web.xml de ce projet (l’extrait relatif aux fichiers de l’exercices). 2022/2023 JAKARTA ENTREPRISE EDITION - SELMA BATTI ATTIA 196

×