Taglibs et JSTL - Web Services 33

publicité
Chapitre 3
Les bibliothèques de
balises JSP
et la JSTL
Sommaire
Taglibs et JSTL
 Les bibliothèques de balises JSP
 La JSTL (Java Standard Tag Library)
M.Romdhani, INSAT, Mars 2009
2
Taglibs et JSTL
Les bibliothèques
de balises JSP
M.Romdhani, INSAT, Mars 2009
3
Taglibs et JSTL
Les bibliothèques de balises
 Les bibliothèques de balises personnalisables
(custom tags
 Encapsulent des fonctions complexes à utiliser dans les
JSPs
 Utilisées pour la création d'un contenu dynamique
 Ce sont des classes qui implémentent l'interface Tag du
Pacakge javax.servlet.jsp.tagext
M.Romdhani, INSAT, Mars 2009
4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?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.30: customTagWelcome.jsp
-->
<!-- JSP that uses a custom tag to output content. -->
Taglibs et JSTL
taglib directive to
Usetaglib
Fig.
10.30
include use
tags
in tag JSP
library
<%-- 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>
welcome
Use custom tag
welcome
to insert text in the JSP
</html>
M.Romdhani, INSAT, Mars 2009
5
Taglibs et JSTL
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// 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.*;
WelcomeTag Class
WelcomeTagHandler
Handler
implements interface
Tag by
handler.
extending classTagSupport
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();
JSP containerLines
calls 15-32
method
doStartTag when it encounters
the startingLine
custom
20 tag
// output content
out.print( "Welcome to JSP Tag Libraries!" );
}
Use custom tag handler’s
pageContext to obtain
JSP’sJspWriter object
for outputting text
// rethrow IOException to JSP container as JspException
catch( IOException ioException ) {
throw new JspException( ioException.getMessage() );
}
return SKIP_BODY;
// ignore the tag's body
}
}
M.Romdhani, INSAT, Mars 2009
6
Taglibs et JSTL
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<?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">
<!-- a tag library descriptor -->
Define
custom-tag fileadvjhtp1
library
descriptor
file
.
taglib
.tld
<taglib>
<tlibversion>1.0</tlibversion>
<jspversion>1.1</jspversion>
<shortname>advjhtp1</shortname>
<info>
A simple tab library for the examples
</info>
describes
tag elementLine
18
welcome custom tag
<!-- A simple tag that outputs content -->
<tag>
<name>welcome</name>
Specify custom tag
name and class
<tagclass>
com.deitel.advjhtp1.jsp.taglibrary.WelcomeTagHandler
</tagclass>
<bodycontent>empty</bodycontent>
<info>
Inserts content welcoming user to tag libraries
</info>
</tag>
</taglib>
M.Romdhani, INSAT, Mars 2009
7
Taglibs et JSTL
La JSTL (JSP Standard Tag Library)
et le langage EL
M.Romdhani, INSAT, Mars 2009
8
Taglibs et JSTL
Mais qu'est ce qui ne va pas dans les tags
JSP ?
 The tag-extension protocol is too complicated
doStartTag()
doInitBody()
doEndTag()

doAfterBody()
release()
doCatch()
doFinally()
Tag handler
M.Romdhani, INSAT, Mars 2009
9
Taglibs et JSTL
Organisation JSP/JSTL
Your
web pages
Your application
JSTL
JavaServer Pages (JSP)
Java Servlet API
Java language
M.Romdhani, INSAT, Mars 2009
10
Taglibs et JSTL
JSTL
 Depuis la version JSP 1.2
 Spécification développé par le groupe d’experts JSR 52
 Collection de Tag Librairies personnalisées qui implémentent la plus part des
fonctions communes aux pages web:
 Itérations et conditions (core)
 Formatage des données (format)
 Manipulation de XML (xml)
 Accès au bases de données (sql)
 Utilisation du langage EL (Expression Language)
 Avantages
 Code simple, lisible et facile à maintenir
 Le concepteur de page est libéré de code Java
 Évite au développeur d’écrire à chaque fois les fonctions de bases.
M.Romdhani, INSAT, Mars 2009
11
Taglibs et JSTL
EL: Expression Language

Spécification de EL sous l’autorité du groupe d’expert JSR-152
pour JSP 1.3

Le JSR-52 et JSR-152 travail ensemble sur la spécification de
l’Expression Language

En JSTL il est utilisé uniquement dans la valeur d’un attribut:
<prefix:tag attr1="${ expr }" />

Il est invoqué exclusivement via la syntaxe ${ expr }
M.Romdhani, INSAT, Mars 2009
12
EL: Expression Language
Taglibs et JSTL
objets prédéfinies

Un identificateur dans EL fait référence à une variable retourné par l’appel
de pageContext.findAttribute(identificateur) et qui est dans la
portée (scope): page, request, session ou application.
${ var } = pageContext.getAttribute("var")

Objets implicites:
 pageScope, requestScope, sessionScope, applicationScope

Accès au paramètres d’une requête HTTP via param (objet de type Map)
et paramValue

Un objet implicite pageContext qui donne accès aux propriétés
associés au contexte de la page JSP
M.Romdhani, INSAT, Mars 2009
13
EL: Expression Language
Taglibs et JSTL
objets prédéfinies
 In ${param.name}, param is one of a set of implicit objects defined in the
JSP expression language
 Others include:
 pageContext.servletContext
 pageContext.session
 pageContext.request
 pageContext.response
 paramValues
 header
 headerValues
M.Romdhani, INSAT, Mars 2009
14
Taglibs et JSTL
JSTL
core tag library
Fonctions de base

Affichage
<c: out value=" expression " />
<%=
expression %>

Affectation
<c:set value="value" var=" varName " scope=" application " />
<% pageContext.setAttribute("varName",value,SCOPE) %>

Exception java.lang.Throwable
<c:catch [var="varName"] >
actions a surveiller
</c:catch>
<% try{
actions à surveiller
}catch(Throwable varName){}
%>
M.Romdhani, INSAT, Mars 2009
15
Taglibs et JSTL
JSTL
core tag library
Les conditions
1- simple if(cond)
<c:if test="${user.visitCount = = 1}">
<c:out value="Première visite.Bienvenue!" />
</c:if>
<% if(user.visitCount == 1){ %>
<%= "Prmière visite.Bienvenue" %>
<% } %>
2-choix multiple if/else
<c:choose>
<% If(count == 0){ %>
<c:when test="${count == 0}”>
<%= Votre compte est vide %>
Pas de visite!
<% }else{ %>
</c:when>
<%= count+"visiteurs" %>
<c:otherwise>
<% } %>
<c:out value="${count}"/> visiteurs.
</c:otherwise>
</c:choose>
M.Romdhani, INSAT, Mars 2009
16
Taglibs et JSTL
JSTL
core tag library
Les itérations avec la boucle for/while
en JSP
<%@page import="java.util.*" %>
<% Member user = null;
Collection users = session.getAttribute("members");
Iterator it =
users.iterator();
while(it.hasNext()){ user = (Member) it.next();
%> <%= "nom:
"+user.getName() %>
<% } %>
en JSTL
forEach
<c:forEach var=”user” items=”sessionScope.members” [begin] [end] [step]>
<c:out value="nom:
${user.name}" />
</c:forEach>
M.Romdhani, INSAT, Mars 2009
17
Exemple : Code JSP
Taglibs et JSTL
<% Enumeration names=request.getParameterNames();
while (names.hasMoreElements()) {
String pname=(String)names.nextElement();
%>
<p><b><%= pname %>:</b>
<%
String[] values=request.getParameterValues(pname);
for (int n=0; n<values.length; ++n) {
%>
<%= values[n] %>
<%}
}
%>
M.Romdhani, INSAT, Mars 2009
18
Exemple : Code équivalent avec JSTL EL
Taglibs et JSTL
<c:forEach var='parameter' items='${paramValues}'>
<p><b><c:out value='${parameter.key}'/></b>:
<c:forEach var='value' items='${parameter.value}'>
<c:out value='${value}'/>
</c:forEach>
</c:forEach>
•The <c:xxx> tags are from the JSTL
•The ${} elements are expression language evaluations
M.Romdhani, INSAT, Mars 2009
19
Téléchargement