Vous êtes sur la page 1sur 31

Les Java Servlet Pages (JSP)

Thierry Lecroq
(merci à Alexandre Pauchet (INSA Rouen))

Université de Rouen
FRANCE

Thierry Lecroq (Univ. Rouen) JSP 1 / 31


Plan

1 Introduction

2 Fonctionnement

3 Inclusion/Délégation

4 JSP & JavaBeans

5 Standard Tag Library

Thierry Lecroq (Univ. Rouen) JSP 2 / 31


Introduction (1/4)
Description d'une JSP

JSP = Java Servlet Pages


Les JSP sont comparables à PHP
Langage de script côté serveur

Une page JSP contient :


du contenu statique (texte simple, XHTML, XML, . . . )
du code JSP qui produit dynamiquement du contenu

Thierry Lecroq (Univ. Rouen) JSP 3 / 31


Introduction (2/4)
Premier exemple

hello.jsp
<%@ page c o n t e n t T y p e=" t e x t / h t m l ; c h a r s e t =u t f 8 " %>
< ! DOCTYPE html PUBLIC " −//W3C/ /DTD XHTML 1.0 S t r i c t / /EN" " h t t p : / / www . w3 . o r g /TR/
x h t m l 1 /DTD/ x h t m l 1 − s t r i c t . d t d ">
<h t m l>
<h e a d>
< t i t l e >Ma p r e m i&e g r a v e ; r e page JSP</ t i t l e >
</ h e a d>
<b o d y>
<% String p r e n o m=r e q u e s t . g e t P a r a m e t e r ( " p r e n o m " ) ; %>
<h 1>B o n j o u r <%=(p r e n o m != n u l l && p r e n o m . l e n g t h ( ) ! = 0 ) ? p r e n o m : " b e l ( l e ) inconnu ( e
) "%></ h 1>
<% i f ( p r e n o m != n u l l && p r e n o m . e q u a l s ( " l e monde " ) ) { %>
<h 2>B i e n j o u&e a c u t e ; ! ! ! ! </ h 2>
<% } %>
<f o r m a c t i o n =" h e l l o . j s p " m e t h o d=" p o s t ">
< l a b e l >P r&e a c u t e ; nom : </ l a b e l >< i n p u t t y p e =" t e x t " name=" p r e n o m " s i z e =" 3 0 ">
<i n p u t t y p e =" s u b m i t " v a l u e =" e n v o y e r ">
</ f o r m>
</ b o d y>
</ h t m l>

Thierry Lecroq (Univ. Rouen) JSP 4 / 31


Introduction (3/4)
Traduction, compilation, instanciation, . . .

Une JSP est transformée en servlet


Fonctionnement :
1 requête sur une JSP
2 une servlet compare les dates de la JSP et de sa servlet
si la servlet de la JSP est plus ancienne que la page :
I traduction de la JSP en servlet (dérivation)
I compilation de la servlet (cf. répertoire tomcat/work)
3 si la servlet de la page n'a pas encore été chargée
I chargement de la servlet
I instanciation
I initialise la servlet avec la méthode jspInit
4 invocation de la méthode jspService
5 Appel de jspDestroy lors du déchargement de la servlet
Thierry Lecroq (Univ. Rouen) JSP 5 / 31
Introduction (4/4)
Quelques éléments JSP

<%@ ... %> : directives valables pour la page


<%! ... %> : déclarations
<% ... %> : scriptlet (= script : tests, itération, . . . )
<%= ... %> : récupération d'une valeur d'expression
<jsp: include ... /> : inclusion à l'exécution
<jsp:forward ... /> : délégation à un autre composant
<jsp:useBean ... /> : utilisation d'un java bean

Thierry Lecroq (Univ. Rouen) JSP 6 / 31


Fonctionnement (1/11)
Directives de page

Ces directives s'appliquent à la page

Syntaxe
<%@ page directive %>

Exemples
<%@ page isThreadSafe="false" %>
<%@ page contentType="text/plain; charset=UTF-8" %>
<%@ page import="java.io.*, java.util.*" %>

Thierry Lecroq (Univ. Rouen) JSP 7 / 31


Fonctionnement (2/11)
Paramètres d'exécution d'une page JSP

L'exécution d'une JSP est paramétrable via la directive page

<%@ page buer="none|xxxkb"%>


spécie la taille du buer où est renvoyée la réponse
un petit buer allège en charge le serveur d'application et envoie la
réponse plus rapidement.
<%@ page errorPage="le_name"%>
spécie la page (JSP ou non) vers laquelle le serveur d'application
renvoie lorsqu'une exception non gérée est lancée par la JSP.
La directive <%@ page isErrorPage="true|false"%> permet de
spécier si la page de renvoie est une page d'erreur et lui autorise ainsi
la transmission de l'exception pour un éventuel traitement.

Thierry Lecroq (Univ. Rouen) JSP 8 / 31


Fonctionnement (3/11)
Exemple
erreur.jsp
<%@ page c o n t e n t T y p e=" t e x t / h t m l ; c h a r s e t =UTF−8" %>
<%@ page e r r o r P a g e=" e r r e u r . h t m l " %>
< ! DOCTYPE html PUBLIC " −//W3C/ /DTD XHTML 1.0 S t r i c t / /EN" " h t t p : / / www . w3 . o r g /TR/
x h t m l 1 /DTD/ x h t m l 1 − s t r i c t . d t d ">
<h t m l>
<h e a d>
< t i t l e >Ma premiere page j s p</ t i t l e >
</ h e a d>
<b o d y>
<h 1>1 / 0 = <%=1/0 %></ h 1>
</ b o d y>
</ h t m l>

erreur.html
< ! DOCTYPE html PUBLIC " −//W3C/ /DTD XHTML 1.0 S t r i c t / /EN" " h t t p : / / www . w3 . o r g /TR/
x h t m l 1 /DTD/ x h t m l 1 − s t r i c t . d t d ">
<h t m l>
<h e a d>
<m e t a h t t p − e q u i v=" C o n t e n t −Type " c o n t e n t =" t e x t / h t m l ; c h a r s e t =UTF−8" />
< t i t l e >P a g e d ' e r r e u r </ t i t l e >
</h e a d>
<b o d y>
<h1> I l doit y avoir une erreur dans la JSP . . . < / h1>
</b o d y>
</ h t m l >

Thierry Lecroq (Univ. Rouen) JSP 9 / 31


Fonctionnement (4/11)
Déclarations

Les déclarations permettent de dénir des classes, des variables, . . .


Elles seront utilisables dans toute la JSP
Syntaxe
<%!
déclarations
%>

Ces déclarations, sont placées dans la classe au moment de la traduction de


la JSP en Servlet
⇒ les variables sont donc des attributs

Thierry Lecroq (Univ. Rouen) JSP 10 / 31


Fonctionnement (5/11)
Initialisation/Finalisation d'une JSP

Paramétrage de l'initialisation et de la nalisation

Initilisation lors du chargement par le serveur d'application :


public void jspInit()
Finalisation lors du déchargement par le serveur d'application :
public void jspDestroy()

Redénition dans les déclarations JSP


<%! public void j s p I n i t () {
...
}
public void jspDestroy () {
...
}
%>

Utilité : ouverture persistante d'une connexion à une BD, . . .


Thierry Lecroq (Univ. Rouen) JSP 11 / 31
Fonctionnement (6/11)
Scriptlets (scripts)

Utilisation des objets, variables, structures de contrôle, . . .

Syntaxe
<%
script
%>

Les scripts seront placées dans la méthode jspService() qui exécute la


requête (GET, POST, . . . ) eectuée sur la page JSP

Thierry Lecroq (Univ. Rouen) JSP 12 / 31


Fonctionnement (7/11)
Expressions

Insertion de valeurs dans la page résultat

Syntaxe
<%= expression %>

L'expression doit retourner une valeur

Thierry Lecroq (Univ. Rouen) JSP 13 / 31


Fonctionnement (8/11)
Exemple

compteur.jsp
<%@ page i s T h r e a d S a f e=" f a l s e " %>
<%@ page c o n t e n t T y p e=" t e x t / p l a i n ; c h a r s e t =UTF−8" %>
<%@ page i m p o r t =" j a v a . i o . ∗ " %>

<%!
int c o m p t e u r =0;
String fichier ;
public void j s p I n i t () {
try {
f i c h i e r =g e t S e r v l e t C o n t e x t ( ) . g e t R e a l P a t h ( " / c o m p t e u r . t x t " ) ;
FileReader file = new FileReader ( f i c h i e r ) ;
BufferedReader reader = new BufferedReader ( f i l e ) ;
compteur = Integer . parseInt ( reader . readLine () ) ;
reader . close () ;
}
catch ( FileNotFoundException exception ) {}
catch ( IOException exception ) {}
catch ( NumberFormatException exception ) {}
}

...

Thierry Lecroq (Univ. Rouen) JSP 14 / 31


Fonctionnement (9/11)
Exemple

compteur.jsp (n)
...

public void jspDestroy () {


try {
FileWriter file = new FileWriter ( fichier ) ;
PrintWriter writer = new PrintWriter ( f i l e ) ;
w r i t e r . p r i n t l n ( compteur ) ;
writer . close () ;
}
catch ( IOException exception ) {
log (" ErreurServlet : enregistrement de l ' etat impossible pour la JSP
compteur2 . j s p " ) ;
l o g ( " "+e x c e p t i o n ) ;
}
}
%>

<% c o m p t e u r +=1; %>

Le compteur : <%=c o m p t e u r%>

Thierry Lecroq (Univ. Rouen) JSP 15 / 31


Fonctionnement (10/11)
Objets disponibles

Objets directement disponibles dans une JSP

request httpServlet : correspondant à la requête


response : correspondant à la réponse renvoyée
session : permet de gérer une session
out : le ot de sortie de la réponse
application : Servlet application ; contient, entre autres, la méthode
log() pour écrire dans le chier log
pageContext : gestion du contexte et des attributs de la JSP
...

Thierry Lecroq (Univ. Rouen) JSP 16 / 31


Fonctionnement (11/11)
Exemple

log.jsp
<%@ page c o n t e n t T y p e=" t e x t / h t m l ; c h a r s e t =UTF−8" %>
< ! DOCTYPE html PUBLIC " −//W3C/ /DTD XHTML 1.0 S t r i c t / /EN" " h t t p : / / www . w3 . o r g /TR/
x h t m l 1 /DTD/ x h t m l 1 − s t r i c t . d t d ">
<h t m l>
<h e a d>
< t i t l e>E c r i t u r e dans le fichier l o g</ t i t l e >
</ h e a d>
<b o d y>
<%
String phrase = "" ;
i f ( r e q u e s t . g e t P a r a m e t e r ( " p h r a s e " ) != n u l l )
phrase = request . getParameter ( " phrase " ) ;
a p p l i c a t i o n . log ( phrase ) ;
%>
<f o r m a c t i o n =" l o g . j s p " m e t h o d=" g e t ">
< l a b e l >P h r a s e a ecrire dans le fichier log : </ l a b e l >< i n p u t t y p e =" t e x t "
name=" p h r a s e " s i z e =" 3 0 ">
<% o u t . p r i n t l n ( "< i n p u t t y p e =\" s u b m i t \ " v a l u e =\" e n v o y e r \">" ) ; %>
</ f o r m>
</ b o d y>
</ h t m l>

Thierry Lecroq (Univ. Rouen) JSP 17 / 31


Inclusion/Délégation (1/4)
Inclusion

Inclusion d'une page statique ou dynamique dans une JSP

inclusion à la traduction en servlet (= inclusion de texte)


<%@ include file="fichier " %>

inclusion à l'exécution (= inclusion du résultat)


<jsp:include page="fichier " />
ou
<jsp:include page="fichier ">
<jsp:param name="nom " value="valeur "/>
...
</jsp:include>

Thierry Lecroq (Univ. Rouen) JSP 18 / 31


Inclusion/Délégation (2/4)
Exemple
inclusion.jsp

<%@ page c o n t e n t T y p e=" t e x t / h t m l ; c h a r s e t =UTF−8" %>


< ! DOCTYPE html PUBLIC " −//W3C/ /DTD XHTML 1.0 S t r i c t / /EN" " h t t p : / / www . w3 . o r g /TR/
x h t m l 1 /DTD/ x h t m l 1 − s t r i c t . d t d ">
<h t m l>
<h e a d>< t i t l e >JSP avec i n c l u s i o n </ t i t l e ></ h e a d>
<b o d y><%@ include f i l e =" t i t r e . t x t " %>
<p>< j s p : i n c l u d e p a g e=" t e x t e . j s p " /></ p>
<p>< j s p : i n c l u d e p a g e=" p a r a m e t r e . j s p ">
< j s p : param name="nom" v a l u e =" Bob " />
</ j s p : i n c l u d e>
</ p>
</ b o d y>
</ h t m l>

titre.txt

<h 1> T i t r e de la JSP , inclus a partir d ' un fichier t e x t e </h1>

texte.jsp

<%@ page c o n t e n t T y p e=" t e x t / p l a i n ; c h a r s e t =UTF−8" %>


<% o u t . p r i n t l n ( " T e x t e genere par la JSP texte . jsp ") ; %>

parametre.jsp

<%@ page c o n t e n t T y p e=" t e x t / p l a i n ; c h a r s e t =UTF−8" %>


<%
String nom = r e q u e s t . g e t P a r a m e t e r ( "nom" ) ;
out . p r i n t l n ( " S a l u t " + nom ) ;
%>

Thierry Lecroq (Univ. Rouen) JSP 19 / 31


Inclusion/Délégation (3/4)
Délégation

Délégation à un autre composant web

Syntaxe
<jsp:forward page="fichier " />
ou
<jsp:forward page="fichier " />
<jsp:param name="nom " value="valeur "/>
...
</jsp:forward>

Thierry Lecroq (Univ. Rouen) JSP 20 / 31


Inclusion/Délégation (4/4)
Exemple
delegation.jsp
<%@ page c o n t e n t T y p e=" t e x t / h t m l ; c h a r s e t =UTF−8" %>
< ! DOCTYPE html PUBLIC " −//W3C/ /DTD XHTML 1.0 S t r i c t / /EN" " h t t p : / / www . w3 . o r g /TR/
x h t m l 1 /DTD/ x h t m l 1 − s t r i c t . d t d ">
<h t m l>
<h e a d>< t i t l e >JSP avec d e l e g a t i o n</ t i t l e ></ h e a d>
<b o d y>
<j s p : forward p a g e=" p a r a m e t r e . j s p ">
< j s p : param name="nom" v a l u e =" Bob " />
</ j s p : f o r w a r d>
</ b o d y>
</ h t m l>

parametre.jsp
<%@ page c o n t e n t T y p e=" t e x t / h t m l ; c h a r s e t =UTF−8" %>
< ! DOCTYPE html PUBLIC " −//W3C/ /DTD XHTML 1.0 S t r i c t / /EN" " h t t p : / / www . w3 . o r g /TR/
x h t m l 1 /DTD/ x h t m l 1 − s t r i c t . d t d ">
<h t m l>
<h e a d>< t i t l e > A f f i c h a g e d e l e g u e</ t i t l e ></ h e a d>
<b o d y>
<%
String nom = r e q u e s t . g e t P a r a m e t e r ( "nom" ) ;
o u t . p r i n t l n ( "<p>S a l u t " + nom + " ! </ p>" ) ;
%>
</ b o d y>
</ h t m l>

Thierry Lecroq (Univ. Rouen) JSP 21 / 31


JSP & JavaBeans (1/9)
Dénition

Denition (JavaBean)
Classe java respectant certaines conventions (API) faisant d'elle un
composant java réutilisable et facilement intégrable dans des applications.

Les JSP orent des balises pour interagir avec un JavaBean

Thierry Lecroq (Univ. Rouen) JSP 22 / 31


JSP & JavaBeans (2/9)
Contraintes de conception

Pour être un JavaBean, une classe doit :


être Serializable,
posséder un constructeur sans argument,
avoir des accesseurs sur ses attributs respectant des conventions de
nommage ; par exemple :
attribut String name
⇒ public void setName(String)
⇒ public String getName()
contenir les méthodes d'interception d'évènements nécessaires.

Thierry Lecroq (Univ. Rouen) JSP 23 / 31


JSP & JavaBeans (3/9)
Utilisation dans les JSP
<jsp:useBean id="nom " class="classebean " scope="portée 1 " />

<jsp:setProperty name="nom " property="propriété " value="valeur2 "/>


ou <% nom.setPropriété (valeur ) %>

<jsp:setProperty name="nom " property="propriété " param="parametre_r

<jsp:useBean id="nom " class="classebean " scope="portée " >


<jsp:setProperty name="nom " property="propriété " .../>
...
</jsp:useBean>

<jsp:getProperty name="nom " property="propriété " />


ou <%=nom.getPropriété () %>
1
request, page, session ou application
2
String ou expression <%= ... %>
3
si absent param=property, si * règle toutes les propriétés ayant des noms iden-
tiques aux paramêtres de requête
Thierry Lecroq (Univ. Rouen) JSP 24 / 31
JSP & JavaBeans (4/9)
Exemple

UnMessage.java
package libMessage ;

import j a v a . beans . ∗ ;
import java . io .∗;
import java . text .∗;
import java . u t i l .∗;

public class UnMessage implements Serializable {


private static SimpleDateFormat formatter = new S i m p l e D a t e F o r m a t ( "E d MMM y y y y ,
H :m: s " , L o c a l e . FRANCE ) ;
private static Date date = new Date ( ) ;
private String email ;
private String texte ;

public UnMessage ( ) { d a t e . setTime ( System . c u r r e n t T i m e M i l l i s ( ) ) ; }

public String getDate () { return formatter . format ( date ) ; }

public void setEmail ( String email ) { t h i s . e m a i l=e m a i l ; }

public String getEmail () { return email ; }

public void setTexte ( String texte ) { t h i s . t e x t e=t e x t e ; }

public String getTexte () { return texte ; }


}

Thierry Lecroq (Univ. Rouen) JSP 25 / 31


JSP & JavaBeans (5/9)
Exemple

LivreOr.java
package libMessage ;

import j a v a . beans . ∗ ;
import java . u t i l .∗;
import java . io .∗;

public class LivreOr {

private Vector messages ;


private String nomFichier ;

public LivreOr () { }

public void setFichier ( String fichier ) throws FileNotFoundException , IOException


, ClassNotFoundException {
nomFichier = fichier ;
FileInputStream fis ;
ObjectInputStream ois = null ;
try {
fis = new FileInputStream ( nomFichier ) ;
ois = new ObjectInputStream ( f i s ) ;
messages = ( Vector ) o i s . readObject () ;
}
catch ( Exception e) {
messages = new Vector () ;
}
}

...

Thierry Lecroq (Univ. Rouen) JSP 26 / 31


JSP & JavaBeans (6/9)
Exemple

LivreOr.java (n)
...

public void addMessage ( UnMessage msg ) {


m e s s a g e s . a d d ( msg ) ;
}

p u b l i c Vector getMessages () {
r e t u r n messages ;
}

public void e n r e g i s t r e r () throws FileNotFoundException , IOException {


FileOutputStream fos = new FileOutputStream ( nomFichier ) ;
ObjectOutputStream oos = new ObjectOutputStream ( f o s ) ;
oos . w r i t e O b j e c t ( messages ) ;
}
}

Thierry Lecroq (Univ. Rouen) JSP 27 / 31


JSP & JavaBeans (7/9)
Exemple

livredor.jsp
<%@ page c o n t e n t T y p e=" t e x t / h t m l " %>
<%@ page l a n g u a g e=" j a v a " i m p o r t =" l i b M e s s a g e . ∗ " %>

< ! DOCTYPE HTML PUBLIC " −//W3C/ /DTD HTML 4.01 T r a n s i t i o n a l / /EN">
<h t m l>
<h e a d>
< t i t l e>L i v r e d ' o r </ t i t l e >
</h e a d>
<b o d y>
<f o r m a c t i o n= ' l i v r e d o r . j s p ' m e t h o d= 'POST '>
< l a b e l >e m a i l : </ l a b e l >
<i n p u t t y p e= ' t e x t ' name= ' e m a i l ' s i z e = ' 5 0 ' />< b r />
<t e x t a r e a name= ' t e x t e ' r o w s= ' 1 0 ' c o l s = ' 8 0 '> S a i s i s s e z votre message i c i </
t e x t a r e a ><b r />
<i n p u t t y p e= ' s u b m i t ' name= ' s u b m i t ' v a l u e= ' E n v o y e r ' />
</f o r m >

<j s p : useBean i d ="msg " c l a s s =" l i b M e s s a g e . U n M e s s a g e " s c o p e =" p a g e " >


<j s p : s e t P r o p e r t y name="msg " p r o p e r t y ="∗"/>
</ j s p : u s e B e a n >

<j s p : useBean i d =" l i v r e o r " c l a s s =" l i b M e s s a g e . L i v r e O r " s c o p e =" p a g e "/>


<j s p : s e t P r o p e r t y name=" l i v r e o r " p r o p e r t y =" f i c h i e r " v a l u e ="/tmp / m e s s a g e s . t x t "/>

...

Thierry Lecroq (Univ. Rouen) JSP 28 / 31


JSP & JavaBeans (8/9)
Exemple
livredor.jsp (n)
...

<%
i f ( msg != n u l l && msg . g e t E m a i l ( ) != n u l l && ! msg . g e t E m a i l ( ) . e q u a l s ( " " ) ) {
l i v r e o r . a d d M e s s a g e ( msg ) ;
l i v r e o r . e n r e g i s t r e r () ;
}

i f ( l i v r e o r != n u l l && l i v r e o r . g e t M e s s a g e s ( ) != n u l l && ! l i v r e o r . getMessages () .


isEmpty ( ) ) {
f o r ( Object lemsg : l i v r e o r . getMessages () ) {
%>
<t a b l e b o r d e r =" 1 p t ">
< t r>
<t d><%= ( ( U n M e s s a g e ) l e m s g ) . g e t E m a i l ( ) %></ t d>
<t d><%= ( ( U n M e s s a g e ) l e m s g ) . g e t D a t e ( ) %></ t d>
</ t r>
< t r>
<t d c o l s p a n =" 2 ">
< p r e>
<%= ( ( U n M e s s a g e ) l e m s g ) . g e t T e x t e ( ) %>
< p r e>
</ t d>
</ t r>
</ t a b l e>
<% } } %>

</ b o d y>
</ h t m l>

Thierry Lecroq (Univ. Rouen) JSP 29 / 31


JSP & JavaBeans (9/9)
Exemple

Déploiement
Livredor
|_ src
| |_ LivreOr . java
| |_ UnMessage . j a v a
| _ WEB−INF
| |_ classes
| |_ libMessage
| |_ LivreOr . c l a s s
| |_ UnMessage . c l a s s
|_ livredor . jsp

Thierry Lecroq (Univ. Rouen) JSP 30 / 31


Standard Tag Library

Les JSP fournissent une bibliothèque de balises standards répondant


à des besoins de base
Quelques domaines :
Core : balises permettant des fonctionalités de base
XML : balises permettant de manipuler des données XML
I18n : balises permettant de traiter l'internationalisation
Database : balises permettant d'eectuer des requêtes SQL (travail
normalement dédié aux JavaBeans)

Il est possible d'étendre le langage en créant d'autre balises

Thierry Lecroq (Univ. Rouen) JSP 31 / 31

Vous aimerez peut-être aussi