views:

4828

answers:

5

Hi,

I have a java bean like this:

class Person {
  int age;
  String name;
}

I'd like to iterate over a collection of these beans in a JSP, showing each person in a HTML table row, and in the last row of the table I'd like to show the total of all the ages.

The code to generate the table rows will look something like this:

<c:forEach var="person" items="${personList}">
  <tr><td>${person.name}<td><td>${person.age}</td></tr>
</c:forEach>

However, I'm struggling to find a way to calculate the age total that will be shown in the final row without resorting to scriptlet code, any suggestions?

Cheers, Don

A: 

It's a bit hacky, but in your controller code you could just create a dummy Person object with the total in it!

How are you retrieving your objects? HTML lets you set a <TFOOT> element which will sit at the bottom of any data you have, therefore you could just set the total separately from the Person objects and output it on the page as-is without any computation on the JSP page.

Phill Sacre
+3  A: 

Check out display tag. http://displaytag.sourceforge.net/11/tut_basic.html

zmf
+3  A: 

Are you trying to add up all the ages?

You could calculate it in your controller and only display the result in the jsp.

You can write a custom tag to do the calculation.

You can calculate it in the jsp using jstl like this.

<c:set var="ageTotal" value="${0}" />
<c:forEach var="person" items="${personList}">
  <c:set var="ageTotal" value="${ageTotal + person.age}" />
  <tr><td>${person.name}<td><td>${person.age}</td></tr>
</c:forEach>
${ageTotal}
ScArcher2
+1  A: 

ScArcher2 has the simplest sollution. If you wanted something as compact as possible, you could create a tag library with a "sum" function in it. Something like:

class MySum { public double sum(List list) {...} }

In your TLD: sum my.MySum double sum(List)

In your JSP, you'd have something like: <%@ taglib uri="/myfunc" prefix="f" %>

${f:sum(personList)}

James Schek
+7  A: 
Jon-Erik
nice work! Have you been listening to Joel's advice about an easy way to earn reputation? :)
Don
nice answer :-)
toolkit