Sunteți pe pagina 1din 68

Institut Supérieur d’Informatique

Chapitre 2 : Les servlets

Année universitaire 2018-2019


1
C'est quoi une servlet ?

 Les servlets sont des classes Java compilées portables tant au


niveau du code source (car elles respectent les spécifications
sur les Servlets Java) qu’au niveau binaire (car elles sont
compilées en byte-code Java, par définition portable d’une
plate-forme à l’autre sans modification).
 Une servlet produit du contenu dynamique en réponse aux
requêtes portant sur une ou plusieurs URLs.
 En plus de produire du contenu dynamiquement, les servlets
supportent plusieurs fonctionnalités applicatives.

2
Historique …

Produits qui implantent cette norme :


• Tomcat d'Apache,
• Glassfish de Sun/Oracle (implantation de référence),
• JBOSS,
• ...
Historique :
• 4.0 (JEE 8) 2017,
• 3.1 (JEE 7) 2013,
• 3.0 (JEE 6) fin 2009,
• 2.5 (JEE 5) en 2005,
• 2.4 (J2EE 1.4) en 2003,
• ...
• 1.0 en 1997.
3
Les Servlets :comment ça marche ?

• Le serveur Web associe une ou plusieurs URLs à


chaque servlet

• Lorsque ces URLs sont appelées via une requête HTTP


de l'utilisateur, côté client, le conteneur de servlet
(moteur) déclenche la servlet qui s'exécute côté serveur

• La servlet génère une réponse HTML/XML vers le client

4
API Servlet

5
API Servlet

Les classes et les interfaces pour les Servlets


sont définies dans 2 packages :
– javax.servlet
package générique indépendant des
protocoles
– javax.servlet.http
spécifique à HTTP permet la gestion des
sessions

6
Les classes de l'API
• 2 classes abstraites :
– javax.servlet.GenericServlet
– javax.servlet.http.HttpServlet

• qui implémentent 2 interfaces :


– javax.servlet.Servlet
– javax.servlet.ServletConfig

7
Package javax.servlet

javax.servlet Nom Rôle

Définition d'un objet qui permet le renvoi d'une requête vers une autre ressource
RequestDispatcher
du serveur (une autre servlet, une JSP ...)
Servlet Définition de base d'une servlet

ServletConfig Définition d'un objet pour configurer la servlet


Les Définition d'un objet pour obtenir des informations sur le contexte d'exécution de
ServletContext
interfaces la servlet

ServletRequest Définition d'un objet contenant la requête du client

ServletResponse Définition d'un objet qui contient la réponse renvoyée par la servlet

SingleThreadModel Permet de définir une servlet qui ne répondra qu'à une seule requête à la fois

GenericServlet Classe définissant une servlet indépendante de tout protocole

Les classes ServletInputStream Flux permettant la lecture des données de la requête cliente

ServletOutPutStream Flux permettant l'envoi de la réponse de la servlet

SevletException Exception générale en cas de problème durant l'exécution de la servlet


Les
exceptions UnavailableException Exception levée si la servlet n'est pas disponible
8
Package javax.servlet.http

javax.servlet
Nom Rôle
.http

Hérite de ServletRequest : définit un objet contenant une requête selon


HttpServletRequest le protocole http

Les
interfaces Hérite de ServletResponse : définit un objet contenant la réponse de la
HttpServletResponse servlet selon le protocole http

HttpSession Définit un objet qui représente une session

Classe représentant un cookie (ensemble de données sauvegardées par


Cookie le browser sur le poste client)
Les classes
Hérite de GenericServlet : classe définissant une servlet utilisant le
HttpServlet protocole http
9
Les méthodes de la classe HttpServlet

Méthode Rôle

Cette méthode est exécutée par le conteneur lorsque la servlet est


void service (ServletRequest req, sollicitée : chaque requête du client déclenche une seule exécution de
ServletResponse res) cette méthode. Elle pouvant être exécutée par plusieurs threads, il faut
prévoir un processus d'exclusion pour l'utilisation de certaines ressources.

Initialisation de la servlet. Cette méthode est appelée une seule fois après
l'instanciation de la servlet.
void init(ServletConfig conf)
Aucun traitement ne peut être effectué par la servlet tant que l'exécution
de cette méthode n'est pas terminée.

ServletConfig getServletConfig() Renvoie l'objet ServletConfig passé à la méthode init

Cette méthode est appelée lors de la destruction de la servlet. Elle permet


void destroy() de libérer proprement certaines ressources (fichiers, bases de données ...).
C'est le serveur qui appelle cette méthode.

String getServletInfo() Renvoie des informations sur la servlet.

10
Cycle de vie d’une Servlet

New Destroyed

Running
init() destroy()

Le serveur gère ce cycle


...()
service()

doGet()
doDelete()

doPost() doPut()

• On implémente souvent la méthode init (invoquée lors de la


première exécution de la servlet) pour récupérer des
ressources ou paramètres d’initialisation.
11
Cycle de vie d'une servlet

Le cycle de vie d'une servlet est l'ensemble du processus de la création à


la destruction :
• Initialisation de la servlet par l'appel de la méthode init (),
• Servlet appelle la méthode service () pour gérer la demande du client,
• Servlet en appelant destroy () méthode met fin.

Méthode init () :
La méthode init() est appelée par le conteneur à chaque instanciation de
la servlet. Lors de l'instanciation, le conteneur de servlet passe en
argument à la méthode init() un objet ServletConfig permettant de charger
des paramètres de configuration propres à la servlet. En cas d'anomalie
lors de l'appel de la méthode init(), celle-ci renvoie une exception de type
ServletException et la servlet n'est pas initialisée.
public void init(ServletConfig config) throws ServletException

12
Cycle de vie d'une servlet

Appel de la méthode service()


C'est la méthode principale qui exécute la logique métier de l'application et
c'est elle qui est aussi responsable du traitement des requêtes des clients.
Quand une nouvelle requête d'une Servlet arrive, le conteneur génère une
nouvelle Thread; la nouvelle thread exécute la méthode service() puis la
logique métier de l'application ou la tâche prévue de la Servlet.

La définition de la méthode service() est:


public void service(ServletRequest request, ServletResponse response)
throwsServletException, IOException{ }

La méthode service() prend deux arguments "request" de type


ServletRequest et "response" de ServletResponse.
Une requête HTTP peut être de différents type comme GET, POST, PUT,
DELETE, etc; le rôle de la méthode service() de voir la requête HTTP
requise et de faire appel à la méthode adéquate qui peut être doGet, doPost,
doPut, doDelete, etc .
13
Cycle de vie d'une servlet

Méthode doGet ()
le type par défaut de toute requête http est "GET"; cela veut dire que si on ne
spécifie pas un type de requête c'est le type "GET" qui prend en charge la requête
donc la méthode doGet() au sein d'une Servlet. Comme son nom l'indique la
méthode doGet() récupère des données ou des informations du serveur via une ou
plusieurs requêtes. Toutefois on peut aussi envoyer des données ou des
informations au serveur via une requête. La méthode doGet a comme signature:
public void doGet(HttpServletRequest request, HttpServletResponse
response) throwsServletException, IOException { }

Méthode doPost ()
Cette méthode est utilisée pour envoyer des données au Serveur; pour faire des
requêtes HTTP de type POST. Cette méthode code les informations de la même
façon que la méthode GET mais elle envoie les données à la suite des en-têtes
HTTP, dans un champ appelé corps de la requête. De cette façon la quantité de
données envoyées n'est plus limitée, et est connue du serveur grâce à l'en-tête
permettant de connaître la taille du corps de la requête. La signature de la
méthode doPost est:
public void doPost(HttpServletRequest request, HttpServletResponse
response) throwsServletException, IOException { }Méthode destroy ()
14
Cycle de vie d'une servlet

Appel de la méthode destroy () :


Elle est appelée une seule fois, à la fin du cycle de vie de la servlet.
Elle vous permet de désactiver la connexion à la base de Servlet,
arrêtez le fil de fond, une liste ou cliquez sur le compteur Cookie
écrit sur le disque, et d'effectuer d'autres activités de nettoyage
similaires.

La signature de la méthode destroy est:


public void destroy () { // Résiliation du code ... }

15
Exemple de servlet : utilisation des méthodes init et destroy

public class SimpleServlet extends HttpServlet {

@Override
protected void doGet(HttpServletRequest reqest, HttpServletResponse response)
throws ServletException, IOException {
response.getWriter().println("Hello World!");
}
@Override
public void init() throws ServletException {
System.out.println(« La Servlet " + this.getServletName() + " est démarrée …");
}
@Override
public void destroy() {
System.out.println(« La Servlet " + this.getServletName() + " est arrêtée …");
}
}

16
Quelques méthodes de HttpServletRequest

Méthode Rôle
String getMethod() retourne la méthode HTTP
String getRemoteHost() retourne le nom du client
String getRemoteAddr() retourne l'adresse IP du client
String getRemotePort() retourne le port du client
String getParameter(String name) retourne la valeur d'un champ de formulaire HTML
Récupère les valeurs d'un formulaire :une sélection
String[]
multiple (cases à cocher, listes à choix multiples) les
getParameterValues(String Key)
valeurs de toutes les entités sélectionnées
String getServerName() retourne le nom du serveur
String getServerPort() le port sur lequel le serveur écoute
ServletInputStream
Permet d'obtenir un flux pour les données de la requête
getInputStream()
BufferedReader getReader() Idem

Voir le site web : http://www.java2s.com/Code/JavaAPI/javax.servlet.http/HttpServletRequest.htm


17
Exemple 1 : informations client

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class InfoClient extends HttpServlet{
public void doGet
(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException{
res.setContentType("text/plain");
PrintWriter out = res.getWriter();
out.println("Hôte: "+req.getRemoteHost());
out.println("Adresse IP: "+req.getRemoteAddr());
}
}

18
Exemple 2 : informations serveur

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class InfoServeur extends HttpServlet {
public void doGet
(HttpServletRequest req, HttpServletResponse res)
throws ServletException,IOException {
res.setContentType("text/plain");
PrintWriter out = res.getWriter();
out.println("Nom du serveur : " + req.getServerName());
out.print("Serveur utilisé : ");
out.println(getServletContext().getServerInfo());
out.println("Port du serveur : " +
req.getServerPort());
}}

19
Répondre au serveur

HttpServletResponse hérite de ServletResponse :

– utilisé pour construire un message de réponse HTTP


renvoyé au navigateur client

– contient les méthodes nécessaires pour définir : type de


contenu, en-tête et code de retour

– contient un flot de sortie pour envoyer des données


(HTML ou autre) au navigateur

20
Quelques Les méthodes de HttpServletResponse

Méthode Description
String setStatus(int StatusCode) Définit le code de retour de la réponse
void setHeader(String Nom, String
Définit une paire clé/valeur dans les en-têtes
Valeur)
Définit le type MIME de la réponse HTTP, c'est-à-dire le
void setContentType(String type)
type de données envoyées au navigateur
void setContentLength(int len) Définit la taille de la réponse

Retourne un objet PrintWriter permettant d'envoyer du


PrintWriter getWriter() texte au navigateur client. Il se charge de convertir au
format approprié les caractères Unicode utilisés par Java

Définit un flot de données à envoyer au client, par


ServletOutputStream
l'intermédiaire d'un objet ServletOutputStream, dérivé de
getOutputStream()
la classe java.io.OutputStream

void sendredirect(String location) Permet de rediriger le client vers l'URL location

Voir le site web :http://www.java2s.com/Code/JavaAPI/javax.servlet.http/HttpServletResponse.htm


21
Objet réponse : HttpServletResponse

Exemple 1 : écrit un message de type TEXT : Utilisation de la méthode


PrintWriter getWriter()

public class HelloWorldPrintWriter extends HttpServlet {


public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/plain");
PrintWriter out = res.getWriter();
out.println("Premier Message");
out.println(« Voilà comment écrire un message");
out.println("Second Message");}}

Exemple 2 : effectue une re-direction vers un site web : Utilisation de la


méthode sendRedirect(String)

public class SendRedirect extends HttpServlet {


public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.sendRedirect("http://www.google.fr");}}
22
Exemple d'une servlet

01.import java.io.*;
02.import javax.servlet.*;
03.import javax.servlet.http.*;
04.
05.public class MyHelloServlet extends HttpServlet {
06.
07.public void doGet(HttpServletRequest request, HttpServletResponse response)
08.throws IOException, ServletException {
09.response.setContentType("text/html");
10.PrintWriter out = response.getWriter();
11.out.println("<html>");
12.out.println("<head>");
13.out.println("<title>Bonjour tout le monde</title>");
14.out.println("</head>");
15.out.println("<body>");
16.out.println("<h1>Bonjour tout le monde</h1>");
17.out.println("</body>");
18.out.println("</html>");
19.}
20.} 23
Exemple d'une servlet

import java .io .*;


import javax . servlet .*;
import javax . servlet . http .*;
public class HelloServlet extends HttpServlet {
public void doGet ( HttpServletRequest request ,HttpServletResponse response )
throws ServletException , IOException {
// 1. Spécifier le type MIME du contenu de la réponse
response . setContentType (" text / html ");
// 2. Récupère le PrintWriter pour envoyer des données au client
PrintWriter out = response . getWriter ();
// 3. Envoyer l'information au client
out. println ("<html >");
out. println ("<head ><title > Bonjour </ title ></ head >");
out. println ("<body >");
out. println ("<h1 > Bonjour à tous </h1 >");
out. println (" </body ></ html >");
}
public void doPost ( HttpServletRequest request ,HttpServletResponse response )
throws ServletException , IOException {
doGet ( request , response );}}
24
/ / Exception IO
import java.io.IOException ;
/ / pour le flux d’ecriture
import java.io.PrintWriter ;
/ / Exception liée au cycle de vie de la Servlet
import javax.servlet.ServletExcept ion ; Import nécessaire
/ / classes obligatoires
import javax.servlet.http.HttpServlet ;
import javax.servlet.http.HttpServletRequest ;
import javax.servlet.http.HttpServletResponse ;

/ / La servlet herite de la classe HttpServlet


public class Hello extends HttpServlet {
/ / Cette Servlet peut être appelé par une requête HTTP GET
protected void doGet (
HttpServletRequest request , / / contient les infos de la requete
HttpServletResponse response ) / / contient la reponse a construire
throws ServletExcept ion , IOException { / / exceptions
Avant toute chose : spécification du type de la réponse
response . setContentType ( " text / html " ) ;
Récupération du flux d’écriture
PrintWriter out = response . getWriter ( ) ;
Écriture de la réponse html
out.println ( "<HTML><HEAD><TITLE>Hello Client ! </ TITLE>"+
" </HEAD><BODY>Hello Client ! </BODY></HTML>" ) ;
/ / optionnel mais utile s’ il y avait des traitement additionnels
out.close ( ) ; 25
Exemple : Téléchargement de fichier par le client http

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ServletDownload extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
File f=new File("C:/java.doc");
FileInputStream fis=new FileInputStream(f);
response.setHeader("Content-Disposition","attachment;filename=a.doc");
byte[] data=new byte[(int)f.length()];
fis.read(data);
OutputStream os=response.getOutputStream();
os.write(data);
os.close();
fis.close();
}
}
26
L'interface ServletContext

La servlet peut obtenir des informations à partir d'un objet ServletContext retourné par
la méthode getServletContext() d'un objet ServletConfig. L'interface ServletContext
contient plusieurs méthodes dont les principales sont :

Méthode Rôle
String getMimeType(String) Retourne le type MIME du fichier en paramètre
Retourne le nom et le numéro de version du
String getServletInfo()
moteur de servlet

getRequestDispatcher(String path) Retourne un objet de type RequestDispatcher

Retourne la servlet contenant l’attribut en


getAttribute(String nom)
paramètre
Retourne une énumération contenant les noms
getAttributeNames()
des attribut de la servlet
Retourne la valeur du nom de paramètre
getInitParameter(String nom)
d’initialisation

27
Structure d'une application web

28
Description de fichier web.xml
Le fichier /WEB-INF/web.xml est un fichier au format XML qui est le descripteur de
déploiement permettant de configurer : l'application, les servlets, les sessions, les
bibliothèques de tags personnalisés, les paramètres de contexte, les types Mimes, les
pages par défaut, les ressources externes, la sécurité de l'application et des ressources
J2EE.
L'élément racine est le tag <web-app>. Cet élément peut avoir plusieurs tags fils dont
l'ordre d'utilisation doit respecter celui défini dans la DTD utilisée.
Le tag <servlet> permet de définir une servlet.
Le tag <servlet-name> permet de donner un nom à la servlet qui sera utilisé pour le
mapping avec l'URL par défaut de la servlet.
Le tag <display-name> permet de donner un nom d'affichage.
Le tag <description> permet de fournir une description de la servlet.
Le tag <servlet-class> permet de préciser le nom complètement qualifié de la classe
Java dont la servlet sera une instance.
Le tag <init-param> permet de préciser un paramètre d'initialisation pour la servlet. Ce
tag possède les tags fils <param-name>, <param-value>, <description>. Les valeurs
fournies peuvent être retrouvées dans le code de la servlet grâce à la méthode
getInitParameter() de la classe ServletConfig.
Le tag <load-on-startup> permet de préciser si la servlet doit être instanciée lors de
l'initialisation du conteneur. Il est possible de préciser dans le corps de ce tag un numéro
29
de séquence qui permettra d'ordonner la création des servlets.
Exemple de fichier web.xml

Mise en correspondance servlet - URL :


<servlet-mapping>
<servlet-name>UneServletSimple</servlet-name>
<url-pattern>/simple/*</url-pattern>
</servlet-mapping>

<servlet-mapping>
<servlet-name>UneServletSimple</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>

URL traitées par la servlet :


http://serveur-name/application-name/simple/
http://serveur-name/application-name/simple/hello.html
http://serveur-name/application-name/simple/documents/7419.html
http://serveur-name/application-name/simple/hello.php
http://serveur-name/application-name/logout.do
http://serveur-name/application-name/asp.do

30
Utilisez Servlet pour lire les données de formulaire

Récupérer les informations de la Requête

Utiliser les méthodes de HttpServletRequest :

• String getParameter(String key)


• String[] getParameterValues(String key)
• Enumeration getParameterNames()

Pour traiter les données de formulaire, les servlets utilisent des méthodes
différentes en fonction de la situation :
getParameter (): Vous pouvez appeler cette méthode pour obtenir la valeur du
paramètre de forme.
getParameterValues (): Si le paramètre apparaît plus d'une fois, puis appelez la
méthode et renvoyer plusieurs valeurs, telles que des cases à cocher.
getParameterNames (): Si vous souhaitez obtenir une liste complète des
demandes actuelles de tous les paramètres, puis appelez la méthode.

31
Exemple 1

<html>
<head>
<title>Un premier formulaire</title>
</head>
<body>
<form method="get" action="Accueil">
Votre Nom :
<input type="text" name="nom"/>
<input type="submit"/>
</form>
</body>
</html>

32
Exemple 1

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Accueil extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
String nom = req.getParameter("nom");
out.println("<HTML>");
out.println("<HEAD><TITLE>Bonjour</TITLE></HEAD>");
out.println("<BODY>");
out.println("<b>Bonjour </b><b>"+nom+"</b>");
out.println("</BODY></HTML>");
}} 33
Exemple 2

• Un formulaire HTML :
<html><body>
<form action="test" method="POST">
<label>Nom : </label> <input type="text" name="nom" size="15"/><br/>
<label>Prénom : </label> <input type="text" name="prenom" size="15"/><br/>
<label>Statut : </label> <select name="statut" size="1"> <option
value="Etudiant">Etudiant</option> <option value="Prof">Enseignant</option>
</select><br/> <input type="submit" name="boutonOK" value="Valider"/>
</form>
</body></html>

• La servlet test :
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
String nom = request.getParameter("nom");
String prenom = request.getParameter("prenom");
response.setContentType("text/html");
response.getWriter().printf( "<html><body><p>Bonjour %s %s</p></body></html>",
prenom, nom ); }
34
Interface RequestDispatcher

propose deux méthodes


• forward(request, response) : passe le contrôle a une autre servlet,
le flux de sortie produit par la servlet courante est supprimé.
• include(request, response) : inclusion dynamique d’un servlet,
équivalent à un appel de sous-programme.

Exemple
public class ForwardServlet extends HttpServlet {
public void doGet (HttpServletRequest request,HttpServletResponse response)
{
request.setAttribute ("action", "hello");
ServletContext context=getServletConfig().getServletContext().
context.getRequestDispatcher("/hello.jsp").forward(request, response);
}}

35
Servlets 3.0

• Comme on est pas là pour faire du « XML Sitting », le


modèle 3.0 a apporté de nombreuses annotations qui
évitent de remplir le fichier web.xml.
• Pour des applications simples il est facultatif
• Nécessaire encore pour certaines tâches

@WebServlet(urlPatterns = {"/sendFile", "/uploadFile"})


public class UploadServlet extends HttpServlet {
// implémentation de la méthode doPost() ou/et doGet()...

}
@WebServlet(
name = "MyOwnServlet",
description = "This is my first annotated servlet",
urlPatterns = "/processServlet"
)
public class MyServlet extends HttpServlet {
// implémentation de la méthode doPost() ou/et doGet()...
} 36
Annotations Servlets 3.0

@WebServlet( name = "HelloAnnotationServlet",


urlPatterns = {"/helloanno"},
initParams = {@WebInitParam(name="param1",value="value1"),
@WebInitParam(name="param2",value="value2")
})

public class HelloAnnotationServlet extends HttpServlet {..}


Récupération des init params dans doGet() ou doXXX() par :
getInitParameter("param1");

37
Cookies et sessions

38
Gestion de l'état avec cookies et sessions

Introduction

HTTP gère les paires requête/réponse


– ouverture, requête, réponse, fermeture
HTTP : protocole sans états
– aucun historique des différentes requêtes n'est conservé
– les requêtes sont totalement indépendantes les unes des autres
Une application WEB a besoin de savoir :
– quel utilisateur a émis la requête courante
– les requêtes déjà émises par l'utilisateur
– l'état général de l'application : nombre de visites, nombres de
produits vendus,
– Il faut rajouter à HTTP un mécanisme de gestion des états

39
Gestion de l'état avec cookies et sessions

Les cookies

Qu'est ce qu'un cookie ?


Petit fragment d'information textuelle échangé entre le
serveur WEB et le Navigateur
– collection de paires nom/valeur
– chargés dans la mémoire du Navigateur
– les cookies permanents sont aussi sauvegardés dans un
fichier texte sur le client
– Ils font partie de l'en-tête HTTP
Utilisés couramment pour mémoriser les préférences de
l'utilisateur ou même pour l'identifier
40
Gestion de l'état avec cookies et sessions

Anatomie d'un cookie

Partie Description
Name Identité du cookie
Value Valeur du cookie
Domain Nom du domaine qui l'a défini
Path Information sur le chemin
Max Age Temps d'expiration du cookie
Secure Vrai si cookie transmis avec SSL

41
Gestion de l'état avec cookies et sessions
Quelques méthodes de Cookie:

void setValue(String val): définit la valeur du cookie


void setMaxAge(int expSec): l'âge de la cookie en nombre de
secondes . La valeur –1 :expire quand on ferme le navigateur et la
valeur 0 : supprime le cookie
void setPath(String path): définit le chemin
void setSecure(boolean flag): true si SSL, false par défaut
void setDomain(String domaine): définit le domaine

public void setDomain(java.lang.String pattern) Specifies the domain within which this cookie
should be presented. The form of the domain name is specified by RFC 2109. A domain name
begins with a dot (.foo.com) and means that the cookie is visible to servers in a specified Domain
Name System (DNS) zone (for example, www.foo.com, but not a.b.foo.com). By default, cookies
are only returned to the server that sent them. 42
Gestion de l'état avec cookies et sessions

Envoi des cookies

Méthode addCookie() de la classe HttpServletResponse

public void doGet(HttpServletRequest req,HttpServletResponse rep)


{
Cookie c = new Cookie ("Id", "123");
c.setMaxAge(365*24*60*60); // 1 an
rep.addCookie( c );
rep.setContentType("text/html");

}

43
Gestion de l'état avec cookies et sessions
Lecture des cookies
Le navigateur envoie automatiquement les cookies qui correspondent au
domaine (domain) et au chemin (path)
Une servlet peut récupérer les cookies envoyés précédemment au navigateur
– méthode getCookies() de HttpServletRequest
Cookie [ ] cookies = request.getCookies();
String nom = getCookieValue(cookies, "nom", "non trouvé");
...
public static String getCookieValue( Cookie [] cookies, String cookieName, String
defaultValue) {
for(int i=0; i < cookies.length; i++) {
Cookie cookie = cookies[i];
if(cookieName.equals(cookie.getName())
return(cookie.getValue()); }
return(defaultValue); } 44
Exemple

public class CookiesServlet extends HttpServlet {


protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
...
String sessionId = null;
Cookie[] cookies = req.getCookies();
if (cookies != null)
{
for (int i = 0; i < cookies.length; i++)
{
if (cookies[i].getName().equals("sessionid")
{
sessionId = cookies[i].getValue();
}
}
}
if (sessionId == null) {
sessionId = new java.rmi.server.UID().toString();
Cookie c = new Cookie("sessionid", sessionId);
res.addCookie(c);
out.println("Bonjour le nouveau");
} else {
out.println("Encore vous"); ... }}} 45
Gestion de l'état avec cookies et sessions

Les sessions

Une session peut se définir :


– une série d'interactions reliées entre un navigateur et un serveur WEB
– englobe plusieurs requêtes HTTP sur une période donnée
– Utilisées pour mémoriser les actions (requêtes HTTP) d'un utilisateur
unique au cours du temps, exemple : opérations bancaires
Techniques de mémorisation
Pour échanger les données d'identification de la session dans chaque
requête :
– Réécriture d'URL
– Champ de formulaire caché ("hidden")
– Cookies
– Utilisation des sessions avec les HttpSession

46
Gestion de l'état avec cookies et sessions

Réécriture d'URL
Principe :
– ajouter dans la chaîne de requête de la servlet des informations
supplémentaires identifiant la session
<a href="http://www.ati.tn/servlet/foo?uid=789">Acheter</a>
– l'ID utilisateur est transmis en même temps que la requête; il est accédé par
chaque servlet mentionnée qui récupère les informations persistantes (BD,
fichiers) à partir de cet ID
Limitations :
– données volumineuses,
– longueur URL,
– données visibles (sécurité)

Champs de formulaires cachés


Principe :
– on cache les données de session dans des champs "hidden" :
<INPUT TYPE="HIDDEN" NAME="uid“ VALUE=789">
Limitations :
– idem la "réécriture d'URL" sauf pour la sécurité (utilisation de POST)
47
Gestion de l'état avec cookies et sessions

L'interface HttpSession
Les objets HttpSession mémorisent les données de chaque utilisateur
fonctionne comme une table de "hachage" stockée sur le serveur
A chaque ID de session est associé, via la table de hachage, l'ensemble
des informations.
Comment obtenir l'objet de session ?
2 méthodes de HttpServletRequest :
– HttpSession getSession() :
retourne la session courante, si elle n'existe pas, elle est créée
– HttpSession getSession(boolean create) :
idem sauf que la session n'est créée que si create = true, sinon
retourne null
Mémoriser et extraire les données
HttpSession session = request.getSession();
session.putValue( "table", new ArrayList());
ArrayList tab = (ArrayList) session.getValue("table");
48
Méthodes de HttpSession

Méthode Description

long getCreationTime() Retourne l'heure de la création de la session

Object getAttributes(String Retourne l'objet stocké dans la session sous le nom


Name) Name, null s'il n'existe pas
String getId() Retourne l’identifiant de session
void putValue(String Name, Stocke l'objet Value dans la session sous le nom
Object Value) Name
Retourne un tableau contenant le nom de toutes
String[] getValueNames()
les clés de la session
Retourne l'objet stocké dans la session sous le nom
Object getValue(String Name)
Name, null s'il n'existe pas
void invalidate() Supprime la session
Retourne true si la session vient d'être créée, sinon
boolean isnew()
false
49
Méthodes de HttpSession

Méthode Description

void removeValue(String Name) Supprime l'élément Name de la session

void setAttribute(String Name, Stocke l'objet Value dans la session sous le nom
Object Value) Name
int setMaxInactiveInterval(int Définit l'intervalle de temps maximum entre deux
interval) requête avant que la session n'expire
int getMaxInactiveInterval(int Retourne l'intervalle de temps maximum entre
interval) deux requête avant que la session n'expire
String getRequestedSessionId() retourne l'ID de session

boolean retourne true si l'ID de session a été passé dans


isRequestedSessionIdFromCookie() un cookie

retourne true si l'ID des session a été passé dans


boolean
l'URL
isRequestedSessionIdFromURL()
50
Exemple

@WebServlet(name = "ServletSession", urlPatterns = {"/ServletSession"})


public class ServletSession extends HttpServlet {

public void doGet(HttpServletRequest req,HttpServletResponse res) throws IOException


{
PrintWriter out = res.getWriter();
HttpSession session = req.getSession();
String prenom="mohamed";
session.setAttribute("prenom", prenom);
String id = session.getId();
out.println("id= "+id);
boolean b=session.isNew();
out.println("isnew= "+b);
long time=session.getCreationTime();
out.println("temps création= "+time);
long last=session.getLastAccessedTime();
out.println("last= "+last);
session.setMaxInactiveInterval(5);
out.println("max= "+session.getMaxInactiveInterval());
session.getAttribute("prenom");
}
} 51
Exercice
• Compter le nombre de requête dans une
session

52
Solution

public class HttpSessionServlet extends HttpServlet {


protected void doGet (HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType ("text/plain");
PrintWriter out = res.getWriter();
HttpSession session = req.getSession();
Integer count = (Integer) session.getAttribute ("count");
if (count == null)
count = 1;
else
count = count.intValue() + 1;
session.setAttribute ("count", count);
out.println ("Vous avez visité cette page " + count + " fois.");
}
}
53
Bilan servlet

Avantages
• Création de contenu dynamiquement
• Utilisation des paramètres pour des traitements
complexes
• Orchestrateur de site (redirection conditionnelle)
Inconvénient
• Langage inapproprié à la création de page WEB
• Gestion des données de stockage et d’affichage
complexe

Si vous voulez en savoir plus sur les servlets, lisez le tutoriel d'Oracle aux adresses :
• https://docs.oracle.com/javaee/7/api/toc.htm
• https://docs.oracle.com/javaee/7/tutorial/servlets.htm#BNAFD
54
• http://www.javatpoint.com
Annexe

55
Les méthodes de la classe HttpServlet : javax.servlet.http.HttpServlet

Modifier and
Method and Description
Type
doDelete(HttpServletRequest req, HttpServletResponse resp) Called by the server (via the
protected void
service method) to allow a servlet to handle a DELETE request.
doGet(HttpServletRequest req, HttpServletResponse resp) Called by the server (via the service
protected void
method) to allow a servlet to handle a GET request.
doHead(HttpServletRequest req, HttpServletResponse resp) Receives an HTTP HEAD request
protected void
from the protected service method and handles the request.
doOptions(HttpServletRequest req, HttpServletResponse resp) Called by the server (via the
protected void
service method) to allow a servlet to handle a OPTIONS request.
doPost(HttpServletRequest req, HttpServletResponse resp) Called by the server (via the service
protected void
method) to allow a servlet to handle a POST request.
doPut(HttpServletRequest req, HttpServletResponse resp) Called by the server (via the service
protected void
method) to allow a servlet to handle a PUT request.
doTrace(HttpServletRequest req, HttpServletResponse resp) Called by the server (via the service
protected void
method) to allow a servlet to handle a TRACE request.
getLastModified(HttpServletRequest req) Returns the time the HttpServletRequest object was
protected long
last modified, in milliseconds since midnight January 1, 1970 GMT.
service(HttpServletRequest req, HttpServletResponse resp) Receives standard HTTP requests
protected void from the public service method and dispatches them to the doXXX methods defined in this
class.
service(ServletRequest req, ServletResponse res) Dispatches client requests to the protected
void
service method.
56
La différence entre ServletConfig et ServletContext

ServletConfig
ServletConfig available in javax.servlet.*; package
ServletConfig object is one per servlet class
Object of ServletConfig will be created during initialization process of the servlet
This Config object is public to a particular servlet only
Scope: As long as a servlet is executing, ServletConfig object will be available, it will be
destroyed once the servlet execution is completed.
We should give request explicitly, in order to create ServletConfig object for the first time
In web.xml – <init-param> tag will be appear under <servlet-class> tag
ServletContext
ServletContext available in javax.servlet.*; package
ServletContext object is global to entire web application
Object of ServletContext will be created at the time of web application deployment
Scope: As long as web application is executing, ServletContext object will be available,
and it will be destroyed once the application is removed from the server.
ServletContext object will be available even before giving the first request
In web.xml – <context-param> tag will be appear under <web-app> tag

57
Toutes les méthodes de l’interface ServletRequest
Modifier and
Method and Description
Type
void flushBuffer() Forces any content in the buffer to be written to the client.
int getBufferSize() Returns the actual buffer size used for the response.
getCharacterEncoding() Returns the name of the character encoding (MIME charset) used for the body sent in
String
this response.
String getContentType() Returns the content type used for the MIME body sent in this response.

Locale getLocale() Returns the locale specified for this response using the setLocale(java.util.Locale) method.
ServletOutputStre
getOutputStream() Returns a ServletOutputStream suitable for writing binary data in the response.
am
PrintWriter getWriter() Returns a PrintWriter object that can send character text to the client.
boolean isCommitted() Returns a boolean indicating if the response has been committed.
void reset() Clears any data that exists in the buffer as well as the status code, headers.
void resetBuffer() Clears the content of the underlying buffer in the response without clearing headers or status code.
void setBufferSize(int size) Sets the preferred buffer size for the body of the response.
setCharacterEncoding(String charset) Sets the character encoding (MIME charset) of the response being sent to
void
the client, for example, to UTF-8.
setContentLength(int len) Sets the length of the content body in the response In HTTP servlets, this method sets
void
the HTTP Content-Length header.
setContentLengthLong(long len) Sets the length of the content body in the response In HTTP servlets, this
void
method sets the HTTP Content-Length header.
setContentType(String type) Sets the content type of the response being sent to the client, if the response has not
void
been committed yet.
void setLocale(Locale loc) Sets the locale of the response, if the response has not been committed yet.

58
Toutes les méthodes de l’interface HttpServletRequest
Modifier and
Method and Description
Type
void addCookie(Cookie cookie) Adds the specified cookie to the response.
void addDateHeader(String name, long date) Adds a response header with the given name and date-value.
void addHeader(String name, String value) Adds a response header with the given name and value.
void addIntHeader(String name, int value) Adds a response header with the given name and integer value.
boolean containsHeader(String name) Returns a boolean indicating whether the named response header has already been set.
String encodeRedirectUrl(String url) Deprecated. As of version 2.1, use encodeRedirectURL(String url) instead
encodeRedirectURL(String url) Encodes the specified URL for use in the sendRedirect method or, if encoding is not
String
needed, returns the URL unchanged.
String encodeUrl(String url) Deprecated. As of version 2.1, use encodeURL(String url) instead
encodeURL(String url) Encodes the specified URL by including the session ID, or, if encoding is not needed, returns
String
the URL unchanged.
String getHeader(String name) Gets the value of the response header with the given name.
Collection<String> getHeaderNames() Gets the names of the headers of this response.
Collection<String> getHeaders(String name) Gets the values of the response header with the given name.
int getStatus() Gets the current status code of this response.
void sendError(int sc) Sends an error response to the client using the specified status code and clears the buffer.
void sendError(int sc, String msg) Sends an error response to the client using the specified status and clears the buffer.
sendRedirect(String location) Sends a temporary redirect response to the client using the specified redirect location
void
URL and clears the buffer.
void setDateHeader(String name, long date) Sets a response header with the given name and date-value.
void setHeader(String name, String value) Sets a response header with the given name and value.
void setIntHeader(String name, int value) Sets a response header with the given name and integer value.
void setStatus(int sc) Sets the status code for this response.
setStatus(int sc, String sm) Deprecated. As of version 2.1, due to ambiguous meaning of the message parameter. To
void set a status code use setStatus(int), to send an error with a description use sendError(int, String). Sets the status code
and message for this response. 59
Toutes les méthodes de l’interface ServletResponse
Modifier and Type Method and Description
getAsyncContext() Gets the AsyncContext that was created or reinitialized by the most recent invocation of startAsync() or startAsync(ServletRequest,ServletResponse) on this
AsyncContext request.
Object getAttribute(String name) Returns the value of the named attribute as an Object, or null if no attribute of the given name exists.
Enumeration<String> getAttributeNames() Returns an Enumeration containing the names of the attributes available to this request.
String getCharacterEncoding() Returns the name of the character encoding used in the body of this request.
getContentLength() Returns the length, in bytes, of the request body and made available by the input stream, or -1 if the length is not known ir is greater than
int Integer.MAX_VALUE.
long getContentLengthLong() Returns the length, in bytes, of the request body and made available by the input stream, or -1 if the length is not known.
String getContentType() Returns the MIME type of the body of the request, or null if the type is not known.
DispatcherType getDispatcherType() Gets the dispatcher type of this request.
ServletInputStream getInputStream() Retrieves the body of the request as binary data using a ServletInputStream.
String getLocalAddr() Returns the Internet Protocol (IP) address of the interface on which the request was received.
Locale getLocale() Returns the preferred Locale that the client will accept content in, based on the Accept-Language header.
getLocales() Returns an Enumeration of Locale objects indicating, in decreasing order starting with the preferred locale, the locales that are acceptable to the client based on
Enumeration<Locale> the Accept-Language header.
String getLocalName() Returns the host name of the Internet Protocol (IP) interface on which the request was received.
int getLocalPort() Returns the Internet Protocol (IP) port number of the interface on which the request was received.
String getParameter(String name) Returns the value of a request parameter as a String, or null if the parameter does not exist.
Map<String,String[]> getParameterMap() Returns a java.util.Map of the parameters of this request.
Enumeration<String> getParameterNames() Returns an Enumeration of String objects containing the names of the parameters contained in this request.
String[] getParameterValues(String name) Returns an array of String objects containing all of the values the given request parameter has, or null if the parameter does not exist.
String getProtocol() Returns the name and version of the protocol the request uses in the form protocol/majorVersion.minorVersion, for example, HTTP/1.1.
BufferedReader getReader() Retrieves the body of the request as character data using a BufferedReader.
String getRealPath(String path) Deprecated. As of Version 2.1 of the Java Servlet API, use ServletContext.getRealPath(java.lang.String) instead.
String getRemoteAddr() Returns the Internet Protocol (IP) address of the client or last proxy that sent the request.
String getRemoteHost() Returns the fully qualified name of the client or the last proxy that sent the request.
int getRemotePort() Returns the Internet Protocol (IP) source port of the client or last proxy that sent the request.
RequestDispatcher getRequestDispatcher(String path) Returns a RequestDispatcher object that acts as a wrapper for the resource located at the given path.
String getScheme() Returns the name of the scheme used to make this request, for example, http, https, or ftp.
String getServerName() Returns the host name of the server to which the request was sent.
int getServerPort() Returns the port number to which the request was sent.
ServletContext getServletContext() Gets the servlet context to which this ServletRequest was last dispatched.
boolean isAsyncStarted() Checks if this request has been put into asynchronous mode.
boolean isAsyncSupported() Checks if this request supports asynchronous operation.
boolean isSecure() Returns a boolean indicating whether this request was made using a secure channel, such as HTTPS.
void removeAttribute(String name) Removes an attribute from this request.
void setAttribute(String name, Object o) Stores an attribute in this request.
void setCharacterEncoding(String env) Overrides the name of the character encoding used in the body of this request.
AsyncContext startAsync() Puts this request into asynchronous mode, and initializes its AsyncContext with the original (unwrapped) ServletRequest and ServletResponse objects.
startAsync(ServletRequest servletRequest, ServletResponse servletResponse) Puts this request into asynchronous mode, and initializes its AsyncContext with the given 60
AsyncContext request and response objects.
Toutes les méthodes de l’interface HttpServletResponse

Modifier and Type Method and Description


authenticate(HttpServletResponse response) Use the container login mechanism configured for the ServletContext to authenticate the user
boolean
making this request.
String changeSessionId() Change the session id of the current session associated with this request and return the new session id.
String getAuthType() Returns the name of the authentication scheme used to protect the servlet.
String getContextPath() Returns the portion of the request URI that indicates the context of the request.
Cookie[] getCookies() Returns an array containing all of the Cookie objects the client sent with this request.
long getDateHeader(String name) Returns the value of the specified request header as a long value that represents a Date object.
String getHeader(String name) Returns the value of the specified request header as a String.
Enumeration<String> getHeaderNames() Returns an enumeration of all the header names this request contains.
Enumeration<String> getHeaders(String name) Returns all the values of the specified request header as an Enumeration of String objects.
int getIntHeader(String name) Returns the value of the specified request header as an int.
String getMethod() Returns the name of the HTTP method with which this request was made, for example, GET, POST, or PUT.
Part getPart(String name) Gets the Part with the given name.
Collection<Part> getParts() Gets all the Part components of this request, provided that it is of type multipart/form-data.
String getPathInfo() Returns any extra path information associated with the URL the client sent when it made this request.
String getPathTranslated() Returns any extra path information after the servlet name but before the query string, and translates it to a real path.
String getQueryString() Returns the query string that is contained in the request URL after the path.
getRemoteUser() Returns the login of the user making this request, if the user has been authenticated, or null if the user has not been
String
authenticated.
String getRequestedSessionId() Returns the session ID specified by the client.
String getRequestURI() Returns the part of this request's URL from the protocol name up to the query string in the first line of the HTTP request.
StringBuffer getRequestURL() Reconstructs the URL the client used to make the request.
String getServletPath() Returns the part of this request's URL that calls the servlet.
HttpSession getSession() Returns the current session associated with this request, or if the request does not have a session, creates one.
getSession(boolean create) Returns the current HttpSession associated with this request or, if there is no current session and create is true,
HttpSession
returns a new session.
Principal getUserPrincipal() Returns a java.security.Principal object containing the name of the current authenticated user.
boolean isRequestedSessionIdFromCookie() Checks whether the requested session ID came in as a cookie.
boolean isRequestedSessionIdFromUrl() Deprecated. As of Version 2.1 of the Java Servlet API, use isRequestedSessionIdFromURL() instead.
boolean isRequestedSessionIdFromURL() Checks whether the requested session ID came in as part of the request URL.
boolean isRequestedSessionIdValid() Checks whether the requested session ID is still valid.
boolean isUserInRole(String role) Returns a boolean indicating whether the authenticated user is included in the specified logical "role".
login(String username, String password) Validate the provided username and password in the password validation realm used by the web
void
container login mechanism configured for the ServletContext.
void logout() Establish null as the value returned when getUserPrincipal, getRemoteUser, and getAuthType is called on the request. 61
Interface ServletContext

Method Summary
FilterRegistration.DaddFilter(java.lang.String filterName, java.lang.Class<? extends Filter> filterClass)
ynamic Adds the filter with the given name and class type to this servlet context.
FilterRegistration.DaddFilter(java.lang.String filterName, Filter filter)
ynamic Registers the given filter instance with this ServletContext under the given filterName.
FilterRegistration.DaddFilter(java.lang.String filterName, java.lang.String className)
ynamic Adds the filter with the given name and class name to this servlet context.
voidaddListener(java.lang.Class<? extends java.util.EventListener> listenerClass)
Adds a listener of the given class type to this ServletContext.
voidaddListener(java.lang.String className)
Adds the listener with the given class name to this ServletContext.
<T extends
java.util.EventListenaddListener(T t)
er> Adds the given listener to this ServletContext.
void
ServletRegistrationaddServlet(java.lang.String servletName, java.lang.Class<? extends Servlet> servletClass)
.Dynamic Adds the servlet with the given name and class type to this servlet context.
ServletRegistrationaddServlet(java.lang.String servletName, Servlet servlet)
.Dynamic Registers the given servlet instance with this ServletContext under the given servletName.
ServletRegistrationaddServlet(java.lang.String servletName, java.lang.String className)
.Dynamic Adds the servlet with the given name and class name to this servlet context.

<T extends Filter>createFilter(java.lang.Class<T> clazz)


T Instantiates the given Filter class.

<T extends
java.util.EventListencreateListener(java.lang.Class<T> clazz)
er> Instantiates the given EventListener class.
T

<T extends Servlet>createServlet(java.lang.Class<T> clazz)


T Instantiates the given Servlet class.
voiddeclareRoles(java.lang.String... roleNames)
Declares role names that are tested using isUserInRole.
java.lang.ObjectgetAttribute(java.lang.String name)
Returns the servlet container attribute with the given name, or null if there is no attribute by that name.
java.util.Enumerati
on<java.lang.StringgetAttributeNames()
> Returns an Enumeration containing the attribute names available within this ServletContext.

java.lang.ClassLoadgetClassLoader() 62
er Gets the class loader of the web application represented by this ServletContext.
Interface ServletContext
ServletContextgetContext(java.lang.String uripath)
Returns a ServletContext object that corresponds to a specified URL on the server.
java.lang.StringgetContextPath()
Returns the context path of the web application.
java.util.Set<SessionTr
getDefaultSessionTrackingModes()
ackingMode>
Gets the session tracking modes that are supported by default for this ServletContext.
intgetEffectiveMajorVersion()
Gets the major version of the Servlet specification that the application represented by this ServletContext is based on.
intgetEffectiveMinorVersion()
Gets the minor version of the Servlet specification that the application represented by this ServletContext is based on.
java.util.Set<SessionTr
getEffectiveSessionTrackingModes()
ackingMode>
Gets the session tracking modes that are in effect for this ServletContext.
FilterRegistrationgetFilterRegistration(java.lang.String filterName)
Gets the FilterRegistration corresponding to the filter with the given filterName.
java.util.Map<java.lang
.String,? extends getFilterRegistrations()
FilterRegistration> Gets a (possibly empty) Map of the FilterRegistration objects (keyed by filter name) corresponding to all filters registered with this
ServletContext.

java.lang.StringgetInitParameter(java.lang.String name)
Returns a String containing the value of the named context-wide initialization parameter, or null if the parameter does not exist.
java.util.Enumeration<getInitParameterNames()
java.lang.String> Returns the names of the context's initialization parameters as an Enumeration of String objects, or an empty Enumeration if the
context has no initialization parameters.
JspConfigDescriptorgetJspConfigDescriptor()
Gets the <jsp-config> related configuration that was aggregated from the web.xml and web-fragment.xml descriptor files of the
web application represented by this ServletContext.
intgetMajorVersion()
Returns the major version of the Servlet API that this servlet container supports.
java.lang.StringgetMimeType(java.lang.String file)
Returns the MIME type of the specified file, or null if the MIME type is not known.
intgetMinorVersion()
Returns the minor version of the Servlet API that this servlet container supports.
RequestDispatchergetNamedDispatcher(java.lang.String name)
Returns a RequestDispatcher object that acts as a wrapper for the named servlet.
java.lang.StringgetRealPath(java.lang.String path) 63
Gets the real path corresponding to the given virtual path.
Interface ServletContext
ServletContextgetContext(java.lang.String uripath)
Returns a ServletContext object that corresponds to a specified URL on the server.
java.lang.StringgetContextPath()
Returns the context path of the web application.
java.util.Set<SessionTracki
getDefaultSessionTrackingModes()
ngMode>
Gets the session tracking modes that are supported by default for this ServletContext.
intgetEffectiveMajorVersion()
Gets the major version of the Servlet specification that the application represented by this ServletContext is based on.
intgetEffectiveMinorVersion()
Gets the minor version of the Servlet specification that the application represented by this ServletContext is based on.
java.util.Set<SessionTracki
getEffectiveSessionTrackingModes()
ngMode>
Gets the session tracking modes that are in effect for this ServletContext.
FilterRegistrationgetFilterRegistration(java.lang.String filterName)
Gets the FilterRegistration corresponding to the filter with the given filterName.
java.util.Map<java.lang.Stri
ng,? extends getFilterRegistrations()
FilterRegistration> Gets a (possibly empty) Map of the FilterRegistration objects (keyed by filter name) corresponding to all filters registered with this
ServletContext.

java.lang.StringgetInitParameter(java.lang.String name)
Returns a String containing the value of the named context-wide initialization parameter, or null if the parameter does not exist.
java.util.Enumeration<java getInitParameterNames()
.lang.String> Returns the names of the context's initialization parameters as an Enumeration of String objects, or an empty Enumeration if the
context has no initialization parameters.
JspConfigDescriptorgetJspConfigDescriptor()
Gets the <jsp-config> related configuration that was aggregated from the web.xml and web-fragment.xml descriptor files of the web
application represented by this ServletContext.
intgetMajorVersion()
Returns the major version of the Servlet API that this servlet container supports.
java.lang.StringgetMimeType(java.lang.String file)
Returns the MIME type of the specified file, or null if the MIME type is not known.
intgetMinorVersion()
Returns the minor version of the Servlet API that this servlet container supports.
RequestDispatchergetNamedDispatcher(java.lang.String name)
Returns a RequestDispatcher object that acts as a wrapper for the named servlet.
java.lang.StringgetRealPath(java.lang.String path) 64
Gets the real path corresponding to the given virtual path.
Interface ServletContext

java.util.Enumer
ation<Servlet>
getServlets()
Deprecated. As of Java Servlet API 2.0, with no replacement. This method was originally defined to return an
Enumeration of all the servlets known to this servlet context. In this version, this method always returns an empty
enumeration and remains only to preserve binary compatibility. This method will be permanently removed in a
future version of the Java Servlet API.

SessionCookieC
onfig getSessionCookieConfig()
Gets the SessionCookieConfig object through which various properties of the session tracking cookies created
on behalf of this ServletContext may be configured.

voidlog(java.lang.Exception exception, java.lang.String msg)


Deprecated. As of Java Servlet API 2.1, use log(String message, Throwable throwable) instead. This method
was originally defined to write an exception's stack trace and an explanatory error message to the servlet log file.
voidlog(java.lang.String msg)
Writes the specified message to a servlet log file, usually an event log.
voidlog(java.lang.String message, java.lang.Throwable throwable)
Writes an explanatory message and a stack trace for a given Throwable exception to the servlet log file.
voidremoveAttribute(java.lang.String name)
Removes the attribute with the given name from this ServletContext.
voidsetAttribute(java.lang.String name, java.lang.Object object)
Binds an object to a given attribute name in this ServletContext.
boolean setInitParameter(java.lang.String name, java.lang.String value)
Sets the context initialization parameter with the given name and value on this ServletContext.
voidsetSessionTrackingModes(java.util.Set<SessionTrackingMode> sessionTrackingModes)
Sets the session tracking modes that are to become effective for this ServletContext.
65
Quelques MIME de la méthode setContentType :

response.setContentType("text/html");
response.setContentType("image/gif");
response.setContentType("application/pdf");
response.setContentType("application/zip");
response.setContentType("application/javascript");
response.setContentType("application/vnd.ms-excel");

Le site web suivant contient les autres type de MIME :


http://www.freeformatter.com/mime-types-list.html
66
What is difference in ServletRequest.getRequestDispather() and
ServletContext.getRequestDispatcher() in Servlet

Servletrequest.getRequestDispatcher(“url”) means the dispatch is


relative to the current HTTP request. Example code:

RequestDispatcher reqDispObj = request.getRequestDispatcher("/login.jsp");

getServletContext().getRequestDispatcher(“url”) means the dispatch is


relative to the root of the ServletContext.Example code:

RequestDispatcher reqDispObj = getServletContext().getRequestDispatcher("/testApp/login.jsp");

67
Difference in SendRedirect() and RequestDispatcher() in Servlet

SendRedirect
• This is the method of object HttpServlerResponse.
• Request is redirected to client (Browser), and it will process the new URL.
• End User can see on which page, url is redirected.
• In Nutshell, Processing done at client side.
RequestDispatcher
• This object can be accessed from HttpServletRequest.
• Servlet will internally forward the request to another servlet or jsp page.
• End user don’t know that which page is processed internally.
• In Nutshell, Processing done at server side.

68

S-ar putea să vă placă și