UP PREVIOUS NEXT   Technologies Internet et Education, © TECFA
  4. Analyse de requêtes POST avec un servlet

4. Analyse de requêtes POST avec un servlet

Exemple 4-1: Simple calcul (Formulaire + Servlet)

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
 
public class SimpleCalculServlet extends HttpServlet {
 
    public void  doPost ( HttpServletRequest  req, HttpServletResponse  res )
	throws ServletException, IOException {
 
	res.setContentType ( "text/html" );
	PrintWriter  out = res.getWriter ( );
	try {
	    String title = "Simple Calcul Java Servlet";
         ........
	    String  choice = req.getParameter ( "choice" );
	    String  choice2 = req.getParameter ( "choice2" );
         ..........
	    int score = Integer.parseInt(choice) + Integer.parseInt(choice2);
 
	    out.print("<h3>Votre score est de " + score + "</h3>");
         ....

Exemple 4-2: Simple Calcul avec persistance

public class SimpleCalculServlet2 extends HttpServlet {
 
int totScore;
int nClicks;
int moyScore;
  public void  doPost (HttpServletRequest req, HttpServletResponse res)
		throws ServletException, IOException {
 
    ........
 
	    nClicks++;
	    totScore = totScore + score;
	    moyScore = totScore / nClicks;
 
	    out.println("<h3>Le score moyen est " + moyScore + " pour " + nClicks + " participants</h3>");
 
    ...........
 

Exemple 4-3: Simple calcul contrôlant GET (Formulaire + Servlet)

   protected void doGet(HttpServletRequest request,
                         HttpServletResponse response)
        throws ServletException, IOException
    {
        PrintWriter out ;
        response.setContentType("text/html");
        out = response.getWriter();
        String header = "<HTML><HEAD><TITLE>Hello Client!</TITLE></HEAD>";
        out.println(header + "<body>");
        out.println("<h1>Sorry, get is not supported, try use the <a href='/guides/java/staf2x/ex/servlets/simple-calcul.html'>form</a> please !</h1>");
        out.println("</BODY></HTML>");
        out.close();
    }
 

Exemple 4-4: Simple calcul avec all-in-one servlet

String html
 = "<HTML>" + "<HEAD>" +
        "<TITLE>Un simple test avec un All-in-One Java Servlet </TITLE>" +
.....
 "<form action='SimpleCalculServletAllinOne
' method=post>" +
.....
 "<input type='submit' value='Voir le résultat!'>" + "</form><hr>" + .. ;
  
 protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException
    {
        PrintWriter out ;
        response.setContentType("text/html");
        out = response.getWriter();
        out.print(html
);
        out.close();
    }

UP PREVIOUS NEXT -- TIE