从Servlet获取复选框值 [英] Getting checkbox value(s) from a Servlet

查看:439
本文介绍了从Servlet获取复选框值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有MySQL数据库的servlet。它看起来像这样:

这里是它的一段代码:

  out.println(< table id = \main_section \ cellspacing = \1 \bgcolor = \red \>); 
out.println(< tr>);
out.println(< td> NUMBER< / td>);
out.println(< td>付款< / td>);
out.println(< td> RECEIVER< / td>);
out.println(< td> VALUE< / td>);
out.println(< td> CHECKBOX< / td>);
out.println(< / tr>);
out.println(< tr>);
为(INT I = 0; I< ex.getExpenses()大小();我++){
通过out.println( < TD> 中。+ ex.getExpenses()得到(i)+< / td>);

如果(ⅰ大于0&安培;&安培;第(i + 1)%4 == 0){
通过out.println( < TD><输入类型= \复选框\名称= \复选框\>< / td>);
out.println(< / tr>< tr>);



out.println(< / tr>);

我需要做的是创建一个提交按钮,用于计算已检查框的VALUE总和。例如,如果选中NUMBER 1和2,则提交按钮应显示5577.0(值22.0 + 5555.0)的结果。
任何人都可以请帮助我吗?


解决方案

首先,你应该了解的JSP和一个JSP,而不是从servlet生成的HTML标记。



现在为您的问题。这些行中的每一行都来自数据库表。所以这些行中的每一行都应该有一个ID(主键)。将行的ID分配给复选框的值。当您提交表单时,该servlet将收到选中复选框的所有ID。从数据库中获取这些ID对应的值,并对它们进行求和(或者执行一个直接计算总和的查询):

  < input type =checkboxname =checkedRowsvalue =$ {idOfCurrentRow}> 

在处理表单提交的servlet中:

  String [] checkedIds = request.getParameterValues(checkedRows); 


I have a servlet with MySQL database in it. It looks like this:

here is the piece of code for it:

out.println("<table id = \"main_section\" cellspacing=\"1\" bgcolor=\"red\" > ");
out.println ("<tr> ");
out.println("<td >NUMBER</td>");
out.println("<td >PAYMENT</td>");
out.println("<td >RECEIVER</td>");
out.println("<td >VALUE </td>");
out.println("<td >CHECKBOX</td>");
out.println("</tr>");
out.println("<tr>");
for (int i = 0; i < ex.getExpenses().size(); i++) {
    out.println("<td > " + ex.getExpenses().get(i) + "</td>");

    if (i>0 && (i+1)%4==0) {
        out.println("<td><input type=\"checkbox\" name=\"checkbox\"></td>");
        out.println("</tr><tr>");

    }     
}
out.println("</tr>");

What I need to do is to create a submit button that calculates the sum of VALUE of the checked boxes. for instance, if NUMBER 1 and 2 are checked the submit button should give the result of 5577.0 (VALUE 22.0+5555.0). Can anyone please help me with that?

解决方案

First of all, you should learn about JSPs and generate your HTML markup from a JSP rather than from the servlet.

Now for your problem. Each of these rows comes from a database table. So each of these rows should have an ID (primary key). Assign the ID of the row to the value of the checkbox. When you submit your form, the servlet will receive all the IDs of the checked checkboxes. Get the values corresponding from these IDs from the database, and sum them (or execute a query that computes the sum directly):

<input type="checkbox" name="checkedRows" value="${idOfCurrentRow}">

In the servlet handling the form submission:

String[] checkedIds = request.getParameterValues("checkedRows");

这篇关于从Servlet获取复选框值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆