You are on page 1of 14

Java Entreprise Edition : Programmation web

Travaux Pratiques N°2


Traitement des données des formulaires
& Manipulation des Cookies

Objectifs:
A. Traiter les données d’utilisateurs envoyés par des formulaires
B. Bien comprendre la structure d’une requête HTTP et d’une réponse HTTP
C. Bien différencier entre les méthodes GET et POST
D. Manipuler les Cookies

Travail à faire
1-Créer une application Java Web de nom Formulaires
2-Créer un fichier html dont le résultat d’exécution est :

3-Créer un fichier html dont le résultat d'exécution est :

Larbi HASSOUNI 1/14


Les valeurs affichées dans les zones de texte sont des valeurs par défaut.
En cliquant sur le bouton valider on lance l'exécution d'une servlet (TwoParamsGET.java) dont le résultat d'exécution
est:

4-Ecrire un fichier html dont le résultat d'exécution est:

Larbi HASSOUNI 2/14


Les valeurs affichées sont des valeurs par défaut.
En cliquant sur le bouton valider vous lancez l'exécution d'une servlet(TwoParamsPOST.java) dont le résultat d'exécution
est :

5-Ecrire un fichier html dont le résultat d'exécution est:

En cliquant sur le bouton valider, vous lancez l'exécution d'une servlet(ThreeParams.java) dont le résultat d'exécution
est:

Larbi HASSOUNI 3/14


6-Ecrire un fichier html dont le résultat d'exécution est:

Après avoir rempli le formulaire comme ci-dessous

Larbi HASSOUNI 4/14


et cliqué sur le bouton Envoyer, vous lancez l'exécution d'une servlet (ShowParameters.java) dont le résultat
d'exécution est:

7-Ecrire un fichier html dont le résultat d'exécution est:

Larbi HASSOUNI 5/14


Après avoir Rempli le formulaire et cliqué sur le bouton Envoyer, vous lancer une servlet dont le résultat
d'exécution d'une servlet dont le résultat d'exécution est:

8-Ecrire un fichier html dont le résultat d'exécution est:

Larbi HASSOUNI 6/14


Après avoir saisi le script ci-dessous et cliqué sur le bouton Envoyer, vous lancer une servlet(CodePreviewBad.java) dont
le résultat d'exécution est fourni plus en bas.

Résultat d'exécution de la servlet CodePreviewBad.java

9-Ecrire un fichier html dont le résultat d'exécution est:

Larbi HASSOUNI 7/14


Après avoir rempli le formulaire par le script ci-dessous puis cliqué sur le bouton Envoyer, vous lancez une
servlet (CodePreviewGood.java ) dont le résultat d'exécution est fourni plus en bas.

Résultat de la servlet CodePreviewGood.java

10-Proposer une servlet qui manipule les cookies

Larbi HASSOUNI 8/14


Codes sources des fichiers HTML
Fichier : index.html
<!DOCTYPE html>
<html>
<head><title>Servlets : Traitement des formulaire</title>
<meta charset="utf-8">
<link rel="stylesheet"
href="css/styles.css"
type="text/css"/>
</head>
<body>
<table class="title">
<tr><th> <img src="images/lune1.jpg" height="100"></th>
<th>Servlets : Traitement des Formulaires</th>
<th><img src="images/lune2.jpg" height="100" ></th>
</tr>
</table>
<p>
Notes: Cette application ne tourne que sur un serveur d'application qui supporte les servlets 3.0.(Tomcat 7 ou 8,
Glassfish)</p>
<fieldset>
<legend>Formulaires faisant appel à des servlets utilisant GET ou POST</legend>
<ul>
<li><a href="get-form.html">get-form.html</a> Formulaire qui envoie les paramètres à la servlet
TwoParamsGET.</li>
<li><a href="post-form.html">post-form.html</a> Formulaire qui envoie les paramètres à la servlet
TwoParamsPOST</li>
<li><a href="three-params-form.html">three-params-form.html</a>
Formulaire qui envoie les paramètres à la servlet ThreeParams: Ne spécifie l'attribut Method(par défaut
Method="doGet").</li>
</ul>
</fieldset>

<p/>
<fieldset>
<legend>Formulaires faisant appel à des servlets qui manipulent différents types de paramètres</legend>
<ul>
<li><a href="show-parameters-get-form.html">show-parameters-get-form.html</a>
Formulaire qui utilise la méthode GET de la servlet ShowParameters pour accéder aux paramètres de la
requète.</li>
<li><a href="show-parameters-post-form.html">show-parameters-post-form.html</a>
Formulaire qui utilise la méthode POST de la servlet ShowParameters pour accéder aux paramètres de la
requète.</li>
</ul>
</fieldset>

<p/>
<fieldset>
<legend>Formulaires faisant appels à des servlets utilisant un filtre</legend>
<ul>
<li><a href="code-form-1.html">code-form-1.html</a>
Larbi HASSOUNI 9/14
Formulaire qui envoie les données à la servlet CodePreviewBad.
Echoue d'échaper aux caractères HTML.</li>
<li><a href="code-form-2.html">code-form-2.html</a>
Formulaire qui envoie les données à la servlet CodePreviewGood .
Réussit d'échaper aux caractères HTML.</li>
</ul>
</fieldset>
</body></html>

Fichier : styles.css
body { background-color: #fdf5e6; }
a:hover { color: red; }
.title {
margin-left: auto;
margin-right: auto;
border-width: 5px;
border-spacing: 2px;
border-style: outset;
}
.title th {
background-color: #ef8429;
font-size: 28px;
font-family: Arial, Helvetica, sans-serif;
}
th { background-color: #ef8429;
font-size: 18px;
font-family: Arial, Helvetica, sans-serif;
}
td { font-size: 18px;
font-family: Arial, Helvetica, sans-serif;
}
legend {
font-weight: bold;
color: black;
background-color: #eeeeee;
border: 1px solid #999999;
padding: 3px 2px;
}

h2 { color: #440000;
font-weight: bold;
font-size: 18px;
font-family: Arial, Helvetica, sans-serif;
}

Larbi HASSOUNI 10/14


API:
Interface HttpServletRequest
• getParameter
String getParameter(String name)
Returns the value of a request parameter as a String, or null if the parameter does not exist. Request parameters are extra
information sent with the request. For HTTP servlets, parameters are contained in the query string or posted form data.
You should only use this method when you are sure the parameter has only one value. If the parameter might have more than one
value, usegetParameterValues(java.lang.String).
If you use this method with a multivalued parameter, the value returned is equal to the first value in the array returned
by getParameterValues.
If the parameter data was sent in the request body, such as occurs with an HTTP POST request, then reading the body directly
via getInputStream() or getReader() can interfere with the execution of this method.
Parameters:
name - a String specifying the name of the parameter
Returns:
a String representing the single value of the parameter
See Also:
getParameterValues(java.lang.String)

• getParameterValues
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.
If the parameter has a single value, the array has a length of 1.
Parameters:
name - a String containing the name of the parameter whose value is requested
Returns:
an array of String objects containing the parameter's values
See Also:
getParameter(java.lang.String)

• getParameterNames
Enumeration<String> getParameterNames()
Returns an Enumeration of String objects containing the names of the parameters contained in this request. If the request has
no parameters, the method returns an emptyEnumeration.
Returns:
an Enumeration of String objects, each String containing the name of a request parameter; or an
empty Enumeration if the request has no parameters

• getParameterMap
Map<String,String[]> getParameterMap()
Returns a java.util.Map of the parameters of this request.
Request parameters are extra information sent with the request. For HTTP servlets, parameters are contained in the query string or
posted form data.
Returns:

Larbi HASSOUNI 11/14


an immutable java.util.Map containing parameter names as keys and parameter values as map values. The keys in the
parameter map are of type String. The values in the parameter map are of type String array.

• getCookies
Cookie[] getCookies()
Returns an array containing all of the Cookie objects the client sent with this request. This method returns null if no cookies were
sent.
Returns:
an array of all the Cookies included with this request, or null if the request has no cookies

Interface HttpServletResponse
• addCookie
void addCookie(Cookie cookie)
Adds the specified cookie to the response. This method can be called multiple times to set more than one cookie.
Parameters:
cookie - the Cookie to return to the client

Class Cookie
public Cookie(String name,
String value)
Constructs a cookie with the specified name and value.
The name must conform to RFC 2109. However, vendors may provide a configuration option that allows cookie names conforming to
the original Netscape Cookie Specification to be accepted.
The name of a cookie cannot be changed once the cookie has been created.
The value can be anything the server chooses to send. Its value is probably of interest only to the server. The cookie's value can be
changed after creation with the setValue method.
By default, cookies are created according to the Netscape cookie specification. The version can be changed with
the setVersion method.
Parameters:
name - the name of the cookie
value - the value of the cookie
Throws:
IllegalArgumentException - if the cookie name is null or empty or contains any illegal characters (for example, a
comma, space, or semicolon) or matches a token reserved for use by the cookie protocol
See Also:
setValue(java.lang.String), setVersion(int)

• setMaxAge
public void setMaxAge(int expiry)
Sets the maximum age in seconds for this Cookie.
A positive value indicates that the cookie will expire after that many seconds have passed. Note that the value is the maximum age
when the cookie will expire, not the cookie's current age.
A negative value means that the cookie is not stored persistently and will be deleted when the Web browser exits. A zero value causes
the cookie to be deleted.
Parameters:
expiry - an integer specifying the maximum age of the cookie in seconds; if negative, means the cookie is not stored; if
zero, deletes the cookie

Larbi HASSOUNI 12/14


See Also:
getMaxAge()

• getName
public String getName()
Returns the name of the cookie. The name cannot be changed after creation.
Returns:
the name of the cookie

• setValue
public void setValue(String newValue)
Assigns a new value to this Cookie.
If you use a binary value, you may want to use BASE64 encoding.
With Version 0 cookies, values should not contain white space, brackets, parentheses, equals signs, commas, double quotes, slashes,
question marks, at signs, colons, and semicolons. Empty values may not behave the same way on all browsers.
Parameters:
newValue - the new value of the cookie
See Also:
getValue()

• getValue
public String getValue()
Gets the current value of this Cookie.
Returns:
the current value of this Cookie
See Also:
setValue(java.lang.String)

Interface Enumeration<E>
• Method Detail

• hasMoreElements

boolean hasMoreElements()
Tests if this enumeration contains more elements.
Returns:
true if and only if this enumeration object contains at least one more element
to provide; false otherwise.

• nextElement

E nextElement()
Returns the next element of this enumeration if this enumeration object has at least one more element to provide.
Returns:

Larbi HASSOUNI 13/14


the next element of this enumeration.
Throws:
NoSuchElementException - if no more elements exist.

Larbi HASSOUNI 14/14

You might also like