Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
678 views
in Technique[技术] by (71.8m points)

java - Getting checkbox value(s) from a Servlet

I have a servlet with MySQL database in it. It looks like this: enter image description here

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...