Question

I got a table in HTML with a button that submit the values as form post.

<form method=POST action="SendToServlet">

<table>
    <tr>
        <td><input type="text" name="num" value="0" size="5"></td>
            <td><input type="text" name="num" value="0" size="5"></td>
    </tr>

        <tr>
        <td><input type="text" name="num1" value="0" size="5"></td>
            <td><input type="text" name="num1" value="0" size="5"></td>
    </tr>
</table>

<input typw="SUBMIT">

</form>

I get the values of the table in servlet and I put them inside an array list that I send to jsp:

ArrayList<Integer> ArrayList= new ArrayList<Integer>();
Enumeration<String> parameterNames = request.getParameterNames();
    while (parameterNames.hasMoreElements()){
        String parameterName = parameterNames.nextElement();
            String[] values= request.getParameterValues(parameterName);
            for(int i=0; i < values.length; i++){
                ArrayList.add(Integer.valueOf(values[i]));
                }
                request.setAttribute("valuesarray",ArrayList);
        request.getRequestDispatcher("/JSP.jsp").forward(request, response);
        }

And I get them in JSP like this:

<%
    ArrayList<Integer> values= (ArrayList) request.getAttribute("valuesarray");
%>
    <table>
        <tr>
               <%for(int i = 0; i<values.size(); i++){%>
               <td><%=values.get(i) %></td>

             <%}%>
           </tr>
    </table>

But my result is like : 1 2 3 4. How can I show it the same like the HTML table?

My expected output:

1     |   2   |  Total row : 3
3     |   4   |  Total row : 7
-----------------------------
4 Col  6 Col

Thank You in Advance!

Était-ce utile?

La solution

If your table format remains like the one you showed (just change happens in number of tr tags each with two td tags in them):-

<table>
    <tr>
        <td><input type="text" name="num" value="0" size="5"></td>
            <td><input type="text" name="num" value="0" size="5"></td>
    </tr>

        <tr>
        <td><input type="text" name="num1" value="0" size="5"></td>
            <td><input type="text" name="num1" value="0" size="5"></td>
    </tr>
</table>

Then Change your jsp code to this:-

 <%
        ArrayList<Integer> values= (ArrayList) request.getAttribute("valuesarray");
   %>
        <table>
    <%
    int k=0;
    int noOfRows=5;
    int noOftds=4;
    for(int i = 0; i<noOfRows; i++)

            {
        if(k==values.size()){break;}
        %>
                <tr>
                <%for(int j = 0; j<noOftds; j++){%>
                 <td><%=values.get(k) %></td>
                 <%k++%>
    <%          
    }%>
            </tr>
    <%          } %>
    </table>

Edit summary :- I have changed code so that you can specify the no of tr tags and no of td tags in each tr tag using the variables.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top