您的位置:首页 > 其它

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

2006-12-01 10:54 417 查看
前几天朋友问我这个问题,但当时没有时间。这两天忙里偷闲做了一个小例子,用的方法比较笨。

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() {
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息