Correction exercice 01 serie 02 servlet
Correction exercice 01 serie 02 servlet
-
Exercice 01
-
Énoncé
-
Solution
-
Vous pouvez visualiser l’énoncé de l’exercice
import java.io.IOException;
import java.io.PrintWriter;
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 sevletAge
*/
@WebServlet("/sevletAge")
public class sevletAge extends HttpServlet {
private static final long serialVersionUID = 1L;
private String title="Génération d'un formulaire";
private final String[] valeurs={"zéro","un","deux",
"trois","quatre","cinq","six",
"sept","huit","neuf"};
private final String HTML1 =
"<html>" +
"<head>" +
"<title>Génération de formulaire</title>"+
"</head>" +
"<body>" +
"<h3>Choississez un nombre</h3>"+
"<hr>" +
"<form method=\"POST\">";
private final String HTML2="<input type=\"submit\"
value=\"Envoyer\">";
private final String HTML3="</form>\n</body>\n</html>";
/**
* @see HttpServlet#HttpServlet()
*/
public sevletAge() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request,
HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
// on indique au client le type de document envoyé
response.setContentType("text/html");
// on envoie le formulaire
PrintWriter out=response.getWriter();
// début
out.println(HTML1);
// combo
out.println("<select name=\"cmbValeurs\" size=\"1\">");
for (int i=0;i<valeurs.length;i++){
out.println("<option>"+valeurs[i]+"</option>");
}//for
out.println("</select>");
// fin formulaire
out.println(HTML2+HTML3);
}//GET
/**
* @see HttpServlet#doPost(HttpServletRequest request,
HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
// on récupère le choix de l'utilisateur
String choix=request.getParameter("cmbValeurs");
if(choix==null) doGet(request,response);
// on prépare la réponse
String réponse="<html><head><title>Voici ma
réponse</title></head>";
réponse+="<body>Vous avez choisi le nombre <h2>"
+choix+"</h2></body></html>";
// on indique au client le type de document envoyé
response.setContentType("text/html");
// on envoie le formulaire
PrintWriter out=response.getWriter();
out.println(réponse);
}
}