Funereal
Funereal

Reputation: 673

Working with Java beans and Servlet values dynamically

I have a table that sends a form post of 5 input text with values to servlet. In servlet I get the values and set them into bean class, and the sum that I set it too to bean class as sum.Then I get the values and the sum on the jsp table.The problem, is that now Im creating a button that when I click, I insert a row after the last row, and I want to keep the values too with the sum, How can I do it?

This is my jsp that send the form to Servlet: Test.jsp

<jsp:useBean id="helloBean" scope="request" class="user.HelloBean" />
<form method="post" action="Servlet">
    <table id= "sum_table">
        <tr>
            <td>Test</td>
            <td>Total</td>
            <td>1</td>
            <td>2</td>
            <td>3</td>
            <td>4</td>
            <td>5</td>
        </tr>   
        <tr>
            <td><input type="text" value="Test1" maxlength=25></td>
            <td><input type="text" value="${helloBean.sum}" maxlength=3 readonly="readonly"></td>
            <c:forEach items="${helloBean.values}" var="item">
                <td><input type="text" id="val" name="values" value="${item}" maxlength=2/></td>
            </c:forEach>
        </tr>
    </table>

    <p><input type="submit"/></p>
    <input type="button" id="btnAdd" value="+"/>
</form>

Now I got the values on servlet, calculate the sum and send them to java bean: Servlet.java

HelloBean hello  = new HelloBean();
String[] values = request.getParameterValues("values");

if (values == null) {
    values = new String[5];

    for(int i = 0; i < 5; i++) {
        values[i]= "0";
    }
}

Integer sum = 0;

for (int i = 0; i < values.length; i++) {
    hello.setSum(sum = sum + Integer.valueOf(values[i]));
    hello.setValues(values);
}   

request.setAttribute("helloBean", hello);
request.getRequestDispatcher("/Test.jsp").forward(request, response);

And this is my Bean Class: HelloBean.java

public class HelloBean {
    String[] values;
    Integer sum;

    public Integer getSuma() {return sum;}
    public void setSum(Integer integer) {this.sum = integer;}
    public String[] getValues() {return values;}
    public void setValues(String[] val) {this.values = val;}
}

This is how I add a new row:

$("#btnAdd").click(function () {
    var row = $("#sum_table tbody > tr:last"),
        newRow = row.clone(true);
    newRow.find("input").each(function () {
        var num = +(this.id.match(/\d+$/) || [0])[0] + 1;
        this.id = this.id.replace(/\d+$/, "") + num;
        this.name = this.id;
    });
    newRow.insertAfter(row);
    return false;
});

Thank You in Advance!

Upvotes: 3

Views: 2543

Answers (4)

kazimt9
kazimt9

Reputation: 563

Just Replace with your input code I added "values[]" instead of "values"

You can use it as array and also set keys into it

<input type="text" id="val" name="values[]" value="${item}" maxlength=2/>

Upvotes: 0

Nu2Overflow
Nu2Overflow

Reputation: 699

You can do it this way without using javascript for adding new row, if it helps you.

1) - Add name to the add button

<input type="button" id="btnAdd" ***name="addrow"*** value="+"/>

2) - At Servlet side check if add button is clicked

if (request.getParameter("addrow") != null){
  request.setAttribute("addRow","yes");
}

3) - At Jsp side add below your for loop

<c:if test="${not empty request.addRow}">
   <td><input type="text" id="val" name="values" value="" maxlength=2/></td>
</c:if>

This will add new emty text field whenever you click on the button. NOTE: I did not test this code.

Upvotes: 1

Tusar
Tusar

Reputation: 769

Don't need the Bean class

You can add keyup event for input

<form method="post" action="Servlet">
<table id= "sum_table">
    <tr>
        <td>Test</td>
        <td>Total</td>
        <td>1</td>
        <td>2</td>
        <td>3</td>
        <td>4</td>
        <td>5</td>
    </tr>   
    <tr>
        <td class="test"><input type="text" name="test" value="Test1" maxlength=25></td>
        <td class="sum"><input type="text" name="sum" value="" maxlength=3 readonly="readonly"></td>
        <td><input type="text" name="mark1" value="" maxlength=2 ></td>
        <td><input type="text" name="mark2" value="" maxlength=2 ></td>
        <td><input type="text" name="mark3" value="" maxlength=2 ></td>
        <td><input type="text" name="mark4" value="" maxlength=2 ></td>
        <td><input type="text" name="mark5" value="" maxlength=2 ></td>           

    </tr>
</table>

<p><input type="button" id="btnSubmit" value="Submit"/></p>
<input type="button" id="btnAdd" value="+"/>

        <script>
        $("#btnAdd").click(function () {
            var row = $("#sum_table tbody > tr:last"),
                newRow = row.clone(true);
            newRow.find("input").each(function () {
                var num = +(this.id.match(/\d+$/) || [0])[0] + 1;
                this.id = this.id.replace(/\d+$/, "") + num;
                this.name = this.id;
            });
            newRow.insertAfter(row);
            return false;
        });

        $("#btnSubmit").click(function () {
            $("#sum_table tbody tr").each(function() {
                var row_total = 0; 
                $("td:not('.test'), td:not('.sum') input:text",this).each(function() {
                    var val =$.trim($(this).val());  
                    //console.log('val='+val);
                    if(val!="" && !isNaN(val))
                   row_total += Number(val);
                }); 
                console.log('row_total='+row_total);
                $(".sum :input:text",this).val(row_total);
            });
        });

    </script>

-------------------SERVLET--------------

 String[] test = request.getParameterValues("test");
 String[] sum = request.getParameterValues("sum");

Upvotes: 1

Braj
Braj

Reputation: 46841

Simply put a check on the value of sum in JSP page and based on its value add new row.

pseudo code:

 if sum is not null then
     add a new row in JSP

When page is loaded first time the value of the sum will be null and when redirected by servlet the value is populated and the sum will not be null and a new row is automatically created in the JSP page.


It should be like this and keep in mind the integer overflow problem.

int sum=0;
for (int i = 0; i < values.length; i++) {
    sum = sum + Integer.valueOf(values[i]);
}
hello.setValues(values);
hello.setSum(sum);

It should look like in JSP:

    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

    <tr>
        <td><input type="text" value="Test1" maxlength="25"/></td>
        <c:forEach items="${helloBean.values}" var="item">
            <td><input type="text" name="values" value="${item}" maxlength="2"/></td>
        </c:forEach>
    </tr>
    <c:if test="${helloBean.sum != null}">
        <tr>
          <td><input type="text" value="${helloBean.sum}" maxlength="3" readonly="readonly"/></td>
        </tr>
    </c:if>

Some points:

  • ID must be unique in the whole page. Multiple input components are created with the same id val in the loop.
  • Use double quotes around the attribute values of the each tag. Is it typo?
  • property sum is not readable on type user.HelloBean because there is no getSum() method in class.

Upvotes: 1

Related Questions