检查使用JAVA(jsp)选择了哪些复选框

Rah*_*mar 8 html java jsp

我正在尝试创建一个显示带有复选框的简单表单的servlet,当用户选择他想要的复选框数并单击"确认"我的servlet中的POST请求检查已检查了哪些框并查询基于数据库.

我不确定如何在Java中执行此操作,因为用户可以选择1个或更多复选框.如果有人可以通过一个小例子来解释这一点,那就太好了.

我是编程新手,如果我知道怎么做的话会提供代码片段.

小智 8

<%@ page language="java"%>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        <title>JSP Multiple Checkbox</title>
    </head>
    <body>
        <form name="form1" onsubmit="checkBoxValidation()">
            <h3>Select your favorite Fruits</h3>
            <p><input type="checkbox" name="fruit" value="Mango"/>Mango</p>
            <p><input type="checkbox" name="fruit" value="Apple"/>Apple</p>
            <p><input type="checkbox" name="fruit" value="Grapes"/>Grapes</p>
            <p><input type="checkbox" name="fruit" value="Papaya"/>Papaya</p>
            <p><input type="checkbox" name="fruit" value="Lychee"/>Lychee</p>
            <p><input type="checkbox" name="fruit" value="Pineapple"/>Pineapple</p>
            <p><input type="submit" value="submit"/>
        </form>
        <%String fruits[]= request.getParameterValues("fruit");
        if(fruits != null){%>
        <h4>I likes fruit/s mostly</h4>
        <ul><%for(int i=0; i<fruits.length; i++){%>
            <li><%=fruits[i]%></li><%}%>
        </ul><%}%>
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

在Web容器上运行此示例jsp,以获得有关其工作原理的基本概念.您需要将此页面上的显示逻辑移动到表单提交时的servlet代码中.这个例子可以在这里找到.希望这会有所帮助.


Max*_*kov 7

这实际上是HTML表单行为问题.当您选中一个带有"name"属性和不同"value"属性的复选框并按"提交"按钮时,您的浏览器将向服务器发送带有选中复选框值的请求.因此,您可以从此url参数中获取值名称.

例如:

<form name="input" action="html_form_action.asp" method="get">
<input type="checkbox" name="vehicle" value="Bike">I have a bike<br>
<input type="checkbox" name="vehicle" value="Car">I have a car 
<br><br>
<input type="submit" value="Submit">
</form>
Run Code Online (Sandbox Code Playgroud)

如果您同时选中这两个复选框,您的服务器将收到以下参数:

http://example.com/your_page.jsp?vehicle=Bike&vehicle=Car 
Run Code Online (Sandbox Code Playgroud)

之后你可以得到这样的值:

String checkboxValues = request.getParameter("vehicle");
Run Code Online (Sandbox Code Playgroud)

checkboxValues获取以逗号分隔的所有值.


小智 5

在您的servlet中,您将使用getParameter(),如下所示:

request.getParameter( "id_of_checkbox" )
Run Code Online (Sandbox Code Playgroud)

如果未选中该框,则该函数返回null.所以你可以这样做:

boolean myCheckBox = request.getParameter( "id_of_checkbox" ) != null;
Run Code Online (Sandbox Code Playgroud)

现在myCheckBox如果选中则为true,如果未选中则为false.