Table des matières
Un servlet
utilise du code Java
dans lequel est mis du code HTML
ou XML
. Toutes les données de la page étant générées par la servlet
, il est possible de générer du HTML 4.01
ou du HTML 5
sans aucune difficulté.
Tous les exemples ci-dessous utilisent le BeanPersonne.
Cycle de vie
Création du projet
Nécessite un projet de type Dynamic Web Project. Une fois le projet généré, il faut créer la servlet. Pour cela : File|New|Servlet
et choisissez comme Superclass
javax.servlet.http.HttpServlet
. Si la super classe n'est pas disponible, c'est que le Dynamic Web Project
n'a pas été correctement créé. Ensuite cliquez sur Next|Next
et demandez à implémenter les méthodes doGet
et doPost
en fonction des besoins.
La création d'une servlet crée automatiquement un fichier web.xml
.
Si un message de type IWAE0035I No servlets exist to add
apparait sous Gentoo, il faut suivre les instructions de www-servers/tomcat-7.0.29-r1 with Eclipse WST Archive du 20/08/2012 le 27/04/2020, à savoir :
cd /usr/share/tomcat-8/lib ln -s /usr/share/eclipse-ecj-4.4/lib/ecj.jar ln -s /usr/share/tomcat-servlet-api-3.1/lib/el-api.jar ln -s /usr/share/tomcat-servlet-api-3.1/lib/jsp-api.jar ln -s /usr/share/tomcat-servlet-api-3.1/lib/servlet-api.jar
Exemple 1 - La base
- Servlet.java
package com.llgc; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.nio.charset.StandardCharsets; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class Servlet */ @WebServlet ("/Servlet") public class Servlet extends HttpServlet { /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding ("UTF-8"); PrintWriter out = response.getWriter (); response.setContentType ("text/html"); out.println ("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">"); out.println ("<html>"); out.println ("<head>"); out.println ("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">"); out.println ("<title>Insert title here</title>"); out.println ("</head>"); out.println ("<body>"); out.println (" <p>"); if (15 % 2 == 0) { out.print ("15 est un nombre pair."); } else { out.print ("15 est un nombre impair."); } out.println (" <br />"); switch (16 % 2) { case 0: out.print ("16 est un nombre pair."); break; default: out.print ("16 est un nombre impair."); break; } out.println (" </p>"); out.println ("</body>"); out.println ("</html>"); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet (request, response); } }
Rendu :
15 est un nombre impair. 16 est un nombre pair.
Exemple 2 - Utilisation d'un Bean
Le Bean utilisé est celui d'une personne.
- Servlet2.java
package com.llgc; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.nio.charset.StandardCharsets; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class Servlet2 */ @WebServlet ("/Servlet2") public class Servlet2 extends HttpServlet { /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding ("UTF-8"); PrintWriter out = response.getWriter (); response.setContentType ("text/html"); out.println ("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">"); out.println ("<html>"); out.println ("<head>"); out.println ("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">"); out.println ("<title>Insert title here</title>"); out.println ("</head>"); out.println ("<body>"); BeanPersonne perso1 = new BeanPersonne (); perso1.setTaille (170); perso1.setYeuxBleus (true); BeanPersonne perso2 = new BeanPersonne (); perso2.setTaille (160); perso2.setYeuxBleus (false); out.println (" <p>"); out.println (" La personne 1 possède une taille de " + perso1.getTaille () + " cm et"); if (!perso1.isYeuxBleus ()) { out.print ("n'a pas"); } else { out.print ("a"); } out.println (" les yeux bleus.<br />"); out.println (" La personne 2 possède une taille de " + perso2.getTaille () + " cm et"); if (!perso2.isYeuxBleus ()) { out.print ("n'a pas"); } else { out.print ("a"); } out.println (" les yeux bleus."); out.println (" </p>"); out.println ("</body>"); out.println ("</html>"); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet (request, response); } }
Rendu :
La personne 1 possède une taille de 170 cm et a les yeux bleus. La personne 2 possède une taille de 160 cm et n'a pas les yeux bleus.
Exemple 3 - Formulaire avec Bean global et session
- Servlet3.java
package com.llgc; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.nio.charset.StandardCharsets; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class Servlet3 */ @WebServlet ("/Servlet3") public class Servlet3 extends HttpServlet { @Override public void init (ServletConfig config) throws ServletException { BeanPersonne pers = new BeanPersonne (); pers.setTaille (123); config.getServletContext ().setAttribute ("beanApp", pers); super.init (config); } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding ("UTF-8"); PrintWriter out = response.getWriter (); BeanPersonne pers = new BeanPersonne (); request.getSession (true).setAttribute ("beanSession", pers); response.setContentType ("text/html"); out.println ("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">"); out.println ("<html>"); out.println ("<head>"); out.println ("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">"); out.println ("<title>Insert title here</title>"); out.println ("</head>"); out.println ("<body>"); out.println (" <br />"); out.println (" <form method=\"post\" action=\"Servlet3\">"); out.println (" Taille : <input name=\"taille\" type=\"text\" /> <input type=\"submit\""); out.println (" value=\"Submit\" />"); out.println (" </form>"); out.println ("</body>"); out.println ("</html>"); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding ("UTF-8"); PrintWriter out = response.getWriter (); BeanPersonne persApp = (BeanPersonne) getServletContext ().getAttribute ("beanApp"); BeanPersonne persLoc = (BeanPersonne) request.getSession (true).getAttribute ("beanSession"); persLoc.setTaille (Integer.parseInt (request.getParameter ("taille"))); response.setContentType ("text/html"); out.println ("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">"); out.println ("<html>"); out.println ("<head>"); out.println ("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">"); out.println ("<title>Insert title here</title>"); out.println ("</head>"); out.println ("<body>"); out.println (" Valeur par défaut du bean application : " + persApp.getTaille () + ".<br />"); out.println (" Valeur saisie du bean local : " + persLoc.getTaille ()); out.println (" <br />"); out.println ("</body>"); out.println ("</html>"); } }
Rendu du formulaire : Rendu de la réponse :
Valeur par défaut du bean application : 123. Valeur saisie du bean local : 153
Exemple 3b - avec validation des données
Dans le cas d'une servlet
, la vérification des données se fait dans la méthode doPost
. Le Javascript
peut être utilisé en pré-traitement.
Exemple 4 - context-param et init-param
Ajout de 3 context-param
.
- web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <display-name>EL</display-name> <servlet> <servlet-name>Faces Servlet</servlet-name> <servlet-class>javax.faces.webapp.FacesServlet</servlet-class> </servlet> <context-param> <param-name>user</param-name> <param-value>utilisateur</param-value> </context-param> <context-param> <param-name>password</param-name> <param-value>mot de passe</param-value> </context-param> <context-param> <param-name>driver</param-name> <param-value>com.mysql.jdbc.Driver</param-value> </context-param> … </web-app>
- Servlet4.java
package com.llgc; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.nio.charset.StandardCharsets; import javax.servlet.ServletException; import javax.servlet.annotation.WebInitParam; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class Servlet4 */ @WebServlet (urlPatterns = "/Servlet4", initParams = { @WebInitParam (name = "user2", value = "utilisateurServlet") }) public class Servlet4 extends HttpServlet { /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding ("UTF-8"); PrintWriter out = response.getWriter (); response.setContentType ("text/html"); out.println ("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">"); out.println ("<html>"); out.println ("<head>"); out.println ("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">"); out.println ("<title>Insert title here</title>"); out.println ("</head>"); out.println ("<body>"); out.println (" <p>"); out.println ("nom : " + getServletContext ().getInitParameter ("user") + "<br />"); out.println ("pass : " + getServletContext ().getInitParameter ("password") + "<br />"); out.println ("driver : " + getServletContext ().getInitParameter ("driver") + "<br />"); out.println ("nom2 : " + getInitParameter ("user2")); out.println (" </p>"); out.println ("</body>"); out.println ("</html>"); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet (request, response); } }
Rendu :
nom : utilisateur pass : mot de passe driver : com.mysql.jdbc.Driver nom2 : utilisateurServlet
Exemple 5 - Cookies
- Servlet5.java
package com.llgc; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class Servlet5 */ @WebServlet ("/Servlet5") public class Servlet5 extends HttpServlet { /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding ("UTF-8"); PrintWriter out = response.getWriter (); String value = getCookie (request.getCookies (), "compteur"); response.setContentType ("text/html"); int compteur = 0; out.println ("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">"); out.println ("<html>"); out.println ("<head>"); out.println ("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">"); out.println ("<title>Insert title here</title>"); out.println ("</head>"); out.println ("<body>"); out.println (" <p>"); if (value == null) { out.println ("Pas de cookie, allez cuisiner !!!"); } else { compteur = Integer.parseInt (value); out.println ("compteur : " + compteur); } out.println (" </p>"); out.println ("</body>"); out.println ("</html>"); compteur++; Cookie c = new Cookie ("compteur", "" + compteur); c.setMaxAge (3600); response.addCookie (c); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet (request, response); } // Renvoie la valeur d'un cookie. protected static String getCookie (Cookie[] cookies, String cookieName) { if (cookies == null) { return null; } for (int i = 0; i < cookies.length; i++) { if (cookieName.equalsIgnoreCase (cookies[i].getName ())) { return cookies[i].getValue (); } } return null; } }
Rendu 1 :
Pas de cookie, allez cuisiner !!!
Rendu 2 :
compteur : 1
Exemple 6 - Affichage d'une liste dans un tableau
La liste est générée par une classe Java et affiche un type BeanPersonne.
- Liste6.java
package com.llgc; import java.util.LinkedList; import java.util.List; @ManagedBean public class Liste6 { public static List <BeanPersonne> getListePersonne () { LinkedList <BeanPersonne> liste = new LinkedList <> (); BeanPersonne personne = new BeanPersonne (); personne.setTaille (160); personne.setYeuxBleus (true); liste.add (personne); personne = new BeanPersonne (); personne.setTaille (170); personne.setYeuxBleus (true); liste.add (personne); personne = new BeanPersonne (); personne.setTaille (180); personne.setYeuxBleus (false); liste.add (personne); return liste; } }
- Servlet6.java
package com.llgc; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class Servlet6 */ @WebServlet("/Servlet6") public class Servlet6 extends HttpServlet { /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding ("UTF-8"); PrintWriter out = response.getWriter (); response.setContentType ("text/html"); List <BeanPersonne> liste = Liste6.getListePersonne (); out.println ("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">"); out.println ("<html>"); out.println ("<head>"); out.println ("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">"); out.println ("<title>Insert title here</title>"); out.println ("</head>"); out.println ("<body>"); out.println (" <p>"); out.println (" <table border=\"1\">"); out.println (" <tr>"); out.println (" <td>Taille</td>"); out.println (" <td>Yeux bleus</td>"); out.println (" </tr>"); for (BeanPersonne beanPersonne : liste) { out.println (" <tr>"); out.println (" <td>" + beanPersonne.getTaille () + "</td>"); out.println (" <td>" + beanPersonne.isYeuxBleus () + "</td>"); out.println (" </tr>"); } out.println (" </table>"); out.println (" </p>"); out.println ("</body>"); out.println ("</html>"); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }