Documente Academic
Documente Profesional
Documente Cultură
2
Historique …
4
API Servlet
5
API Servlet
6
Les classes de l'API
• 2 classes abstraites :
– javax.servlet.GenericServlet
– javax.servlet.http.HttpServlet
7
Package javax.servlet
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
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
Les classes ServletInputStream Flux permettant la lecture des données de la requête cliente
javax.servlet
Nom Rôle
.http
Les
interfaces Hérite de ServletResponse : définit un objet contenant la réponse de la
HttpServletResponse servlet selon le protocole http
Méthode Rôle
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.
10
Cycle de vie d’une Servlet
New Destroyed
Running
init() destroy()
doGet()
doDelete()
doPost() doPut()
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
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
15
Exemple de servlet : utilisation des méthodes init et destroy
@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
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
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
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 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
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
<servlet-mapping>
<servlet-name>UneServletSimple</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
30
Utilisez Servlet pour lire les données de formulaire
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
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
}
@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
37
Cookies et sessions
38
Gestion de l'état avec cookies et sessions
Introduction
39
Gestion de l'état avec cookies et sessions
Les cookies
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:
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
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
Les sessions
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é)
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
Méthode Description
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
52
Solution
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
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
java.util.EventListencreateListener(java.lang.Class<T> clazz)
er> Instantiates the given EventListener class.
T
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.
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");
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