不定数量的CheckBox如何判断用户是否选中

本文提供了一个使用JSP和Servlet实现动态生成复选框的例子。该示例展示了如何通过服务器端代码动态创建指定数量的复选框,并将这些复选框组织成表格形式。此外,还介绍了如何在Servlet中获取并处理用户提交的选择。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前几天朋友问我这个问题,但当时没有时间。这两天忙里偷闲做了一个小例子,用的方法比较笨。

JSP:
<%@page contentType="text/html; charset=GBK"%>
<html>
<head>
<title>Dynamic Checkbox</title>
</head>
<body bgcolor="#ffffff">
<h1>Dynamic Checkbox</h1>
<%
  int count = 20;                     CheckBox的数量
  String ident = "check_box";    CheckBox的标识名
%>
<form method="post" action="dservlet">
<input type="hidden" name="ident" value="<%=ident%>"/>
<input type="hidden" name="count" value="<%=count%>"/>
<table border="1">
<%
  String result = "";
  for (int i = 0; i < count; i++) {
    if (i % 5 == 0) {
      result += "</tr><tr>";
    }
    result += "<td><input type='checkbox' name='" + ident + i + "' value='" + ident + i + "'/>" + ident + i + "</td>";
  }
  out.println(result.replaceFirst("</tr>", ""));
%>
  <tr>
    <td>
      <input type="submit" name="Submit" value="Submit">
      <input type="reset" value="Reset">
    </td>
  </tr>
</table>
</form>
</body>
</html>

 Servlet:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;

public class DServlet extends HttpServlet {
    private static final String CONTENT_TYPE = "text/html; charset=GBK";

    //Initialize global variables
    public void init() throws ServletException {
    }

    //Process the HTTP Get request
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws
            ServletException, IOException {
        response.setContentType(CONTENT_TYPE);
        String ident = request.getParameter("ident");
        int count = Integer.parseInt(request.getParameter("count"));
        PrintWriter out = response.getWriter();
        for (int i = 0; i < count; i++) {
            String value = request.getParameter(ident + i);
            if (value != null && !value.equals("null")) {
                out.println(value);
            }
        }

        out.close();
    }

    //Process the HTTP Post request
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws
            ServletException, IOException {
        doGet(request, response);
    }

    //Clean up resources
    public void destroy() {
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值