Getting flag values ​​(s) from a servlet

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

here is the code snippet 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 create a submit button that calculates the VALUE amount from the marked fields. for example, if NUMBER 1 and 2 are checked, the submit button should return 5577.0 (VALUE 22.0 + 5555.0). Can someone help me with this?

+6
source share
3 answers

First of all, you should learn about JSP and generate your HTML markup from JSP, not from a servlet.

Now for your problem. Each of these rows comes from a database table. Therefore, each of these lines must have an identifier (primary key). Set the row ID to the value of this flag. When you submit your form, the servlet will receive all the identifiers of the checked flags. Get the values ​​corresponding to these identifiers from the database and sum them up (or run a query that calculates the amount directly):

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

In the servlet that processes the form:

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

You can get it

 String[] values = req.getParameterValues("checkbox"); 
+1
source

Change this line:

 out.println("<td><input type=\"checkbox\" name=\"checkbox\"></td>"); 

Count:

 out.println("<td><input type=\"checkbox\" name=\"selected\" value=\""+ex.getExpenses().get(i-1)+"\"></td>"); 

This will create checkboxes that you can identify with the value tag. I hope the number field is the primary key or the like.

Then in the next run. You can get all checked values ​​with:

 String[] selected = request.getParameters("selected"); 

now you can just add numbers. I don’t quite understand what the list of expenses from the code looks like. Here is just an illustration that will not work, but can give you an idea of ​​how to do this:

 int sum = 0; for (int i = 0; i < ex.getExpenses().size(); i++) for(int selectedIndex = 0; selectedIndex < selected.length; ++selectedIndex) if (ex.getExpenses().get(i) == Integer.parseInt(selected[selectedIndex])) sum += ex.getExpenses().get(i-1); 
+1
source

Source: https://habr.com/ru/post/916123/


All Articles