Search code examples
javajspservletshtml-tablejstl

How to show the variable values at the top of the table in jsp?


I am passing an object from servlet to jsp and then I am iterating that object in the jsp and showing the results in a table as shown below. And while iterating the table, I calculate some counts and store it in a variable.

These are my count variable -

kCount
rCount
totalCount

And then I am showing the actual values of these count variables in fieldset as shown below and it works fine.

<div>

    <!-- if I try to show the fieldset here, then I see all the values coming as zero. -->

<TABLE>
    <TR>
        <TH>VALUE1</TH>
        <TH>VALUE2</TH>
        <TH>VALUE3</TH>
        <TH>VALUE4</TH>
    </TR>

    <c:set var="kCount" value="0" scope="page"/>
    <c:set var="rCount" value="0" scope="page"/>
    <c:set var="totalCount" value="${CV.getValue().size()}" scope="page"/>

    <c:forEach var="i" begin="0" end="${CV.getValue().size() - 1}">
        <TR>
            <TD>
                ${CV.getValue().get(i)}
            </TD>
            <TD>
            ${CV.getHasR().get(i)}
            <c:if test="${CV.getHasR().get(i) == 'True'}">
                <c:set var="rCount" value="${rCount + 1}" scope="page"/>
            </c:if>
            </TD>
            <TD>
            ${CV.getType().get(i)}
            <c:if test="${CV.getType().get(i) == 'K'}">
                <c:set var="kCount" value="${k + 1}" scope="page"/>
            </c:if>
            </TD>
        </TR>
    </c:forEach>
</TABLE>

    <!-- I don't want to show the fieldset here, it should be shown at the top of the table -->
    <fieldset>
        <legend><b>Window</b></legend>
        <table>
            <tr>
                <th>VALUE2</th>
                <th>VALUE3</th>
            </tr>
            <tr>
                <td>Total rows:</td>
                <td>${totalCount}</td>
            </tr>
            <tr>
                <td>R Count:${rCount}</td>
                <td>K count:${kCount}</td>
            </tr>
        </table>
    </fieldset>
</div>

Now If I try to copy this fieldset and try to show at the top of the table instead of showing at the bottom of the table, then I see all the values as zero. My main goal is to show the values of each variables in the fieldset but it should be shown at the top of the table, not at the bottom.

Any thoughts how this can be one if possible at all?


Solution

  • There are at least three options here (I am sure there are many more):

    1. Calculate your totals in the servlet and pass them to the JSP for display
    2. In the JSP, loop through your data first to calculate the totals and display them, then loop again to display the data
    3. In the JSP, loop through and display your data while calculating your totals, then use jQuery or similar to write the totals back into the correct location using javascript.