日期:2014-05-17  浏览次数:20805 次

一个来访统计的问题。。
Java code

<body>
        <fieldset>
            <legend>来访调查:</legend>
            <form action="NewServlet" target="_blank" method="post" >
                <label>姓名:<input type="text" name="visitor"></label>
                <label>性别:<input type="text" name="Sex"></label>
                <input type="submit" value="统计">
            </form>
        </fieldset>

      
    </body>


Java code

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Administrator
 */
public class NewServlet extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
                
            /* TODO output your page here
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet NewServlet</title>");  
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet NewServlet at " + request.getContextPath () + "</h1>");
            out.println("</body>");
            out.println("</html>");
             */
         
         int num1, num2, sum;
            num1 = 0;
            num2 = 0;
            sum = 0;
            try {
                if ((request.getParameter("Sex")).equals("Female")) {
                    num1 = num1 + 1;
                } else if ((request.getParameter("Sex")) == "Male") {
                    num2 = num2 + 1;
                }
            } catch (Exception e) {
                out.print("参数不对或无输入");
                return;
            }
            out.println(num1);
            sum=num1+num2;
         out.println(sum);
        } finally {
            out.close();
        }
    }
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">

    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException,
            IOException {
        processRequest(request,