Java Servlet:如何检索选定的单选按钮值?

Php*_*ete 6 java servlets radio-button

我创建了一个简单的servlet,在其中向用户呈现2个问题,回答真或假.我的问题在于检索用户选择的答案.

码:

            out.println("<FORM ACTION=\"Game\" METHOD = \"POST\">" +

        "<b>Question 1: Are you over the age of 25? </b><br> <br>" +

        "<input type = \"radio\" name = \"Q1rad1\" onclick = \"getAnswer('a')\"> True " +
        "<input type = \"radio\" name = \"Q1rad2\" onclick = \"getAnswer('b')\"> False<br>" +

        "<br><br><b>Question 2: Are you from earth?</b><br> <br>" +

        "<input type = \"radio\" name = \"Q2rad1\" onclick = \"getAnswer('a')\"> True " +
        "<input type = \"radio\" name = \"Q2rad2\" onclick = \"getAnswer('b')\"> False<br>" +

        out.println("<Center><INPUT  TYPE=\"SUBMIT\"></Center>");


        );
Run Code Online (Sandbox Code Playgroud)

每个问题都有2个单选按钮,Q1rad1和Q2rad2,用于回答真或假.按下提交按钮时,如何知道每个用户选择的值.

我知道使用Javascript时效率可能更高,但出于这个问题的目的,我必须使用servlet.

and*_*dih 14

选择单选按钮时,必须定义要检索的值

设置定义,如果查了一下将被提交.

名称设置告诉字段属于哪个单选按钮组.选择一个按钮时,同一组中的所有其他按钮都将被取消选中.

<input type = "radio" name = "Q2" onclick = \"getAnswer('b') value="b">
<input type = "radio" name = "Q2" onclick = \"getAnswer('a') value="a">
Run Code Online (Sandbox Code Playgroud)

在您的Servlet中,您将收到类似的请求

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // get the value of the button group 
    String q2 = request.getParameter("Q2");
    // compare selected value 
    if ("a".equals(q2)) {
       ...
    }
    ...

}
Run Code Online (Sandbox Code Playgroud)


Asa*_*aph 6

您尚未正确命名单选按钮.同一问题的每个无线电选项都需要相同的名称属性.此外,您应该value在每个上都有一个属性<input type="radio">.我不确定你是否需要onclick处理程序.你也应该有一个</form>更接近的标签.您的表单可能如下所示:

 out.println("<form action=\"Game\" method=\"POST\">" +

    "<b>Question 1: Are you over the age of 25? </b><br> <br>" +

    "<input type = \"radio\" name = \"Q1\" value=\"True\"> True " +
    "<input type = \"radio\" name = \"Q1\" value=\"False\"> False<br>" +

    "<br><br><b>Question 2: Are you from earth?</b><br> <br>" +

    "<input type = \"radio\" name = \"Q2\" value=\"True\"> True " +
    "<input type = \"radio\" name = \"Q2\" value=\"False\"> False<br>" +

    "<Center><INPUT  TYPE=\"SUBMIT\"></Center>" +

    "</form>"
    );
Run Code Online (Sandbox Code Playgroud)

然后在doPost()处理表单提交的servlet方法中,您可以使用访问值request.getParameter().像这样的东西:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String q1 = request.getParameter("Q1");
    String q2 = request.getParameter("Q2");
    // more processing code...
}
Run Code Online (Sandbox Code Playgroud)


das*_*h1e 3

对同一问题的无线电赋予相同的名称,并设置不同的值。看看这个页面

然后在请求中您将获得一个参数,其中包含单选按钮组的名称和所选值。提交 servlet 后,接收帖子可以使用:

String value = request.getParameter("radioName");
Run Code Online (Sandbox Code Playgroud)