import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.ServletException; import java.io.IOException; import java.io.PrintWriter; import java.util.Arrays; import java.util.Map; import java.util.HashMap; import java.util.Iterator; public class EchoParams extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); Map paramMap = request.getParameterMap(); out.println(reponse("get",paramMap)); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); Map paramMap = request.getParameterMap(); out.println(reponse("post",paramMap)); } // méthodes utilitaires pour générer du html private static String tag(String tag,String contenu){ return "<"+tag+(contenu.length()==0?"/":">"+contenu+""; } private static String tagNL(String tag,String contenu){ return tag(tag,contenu)+"\n"; } private static String html(String contenu){return tagNL("hmtl",contenu);} private static String head(String contenu){return tagNL("head",contenu);} private static String body(String contenu){return tagNL("body",contenu);} private static String title(String contenu){return tag("title",contenu);} private static String i(String contenu){return tag("i",contenu);} private static String tr(String contenu){return tagNL("tr",contenu);} private static String td(String contenu){return tag("td",contenu);} private static String br(){return tagNL("br","");} private static String p(String contenu){return tagNL("p",contenu);} private static String reponse(String methode, Map m){ return html(head(title("Echo Servlet"))+ body(p("Voici le contenu des variables que j'ai reçu" +" par la méthode "+methode)+ lesParams(m)) ); } private static String lesParams(Map m){ StringBuffer sb = new StringBuffer(); sb.append("\n"); // déterminer si c'est une femme... boolean estUneFemme = false; Object leSexe = m.get("sexe"); if(leSexe instanceof String[]){ String[] sexeVals = (String[])leSexe; if(sexeVals.length==1 && sexeVals[0].equals("F")) estUneFemme = true; // ouf, c'est compliqué une femme !! } // for(Iterator i=m.entrySet().iterator();i.hasNext();){ Map.Entry e = (Map.Entry)i.next(); String key = (String)e.getKey(); String[] value = (String[])e.getValue();// longueur 1 si une seule valeur sb.append(tr(td(key)+ td(estUneFemme&&key.equals("age")? "**": ((value.length==1)?value[0]:(""+Arrays.asList(value))) ) )); } sb.append("
"); return ""+sb; } // pour tester isolement public static void main (String[] args){ HashMap m = new HashMap(); Object [][] params = {{"nom",new String[]{"Guy Lapalme","Diane Landry"}}, {"sexe",new String[]{"F"}}, {"age",new String[]{"53"}}}; for(int i=0;i