计算c:forEach循环中所有数字的总和 [英] Calculate total sum of all numbers in c:forEach loop

查看:221
本文介绍了计算c:forEach循环中所有数字的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  class Person {
int age;
字符串名称;



$ b我想在JSP中迭代这些bean的集合,在HTML表格行中显示每个人,并在表格的最后一行中显示所有年龄的总和。



生成表格行将如下所示:

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

然而,我正在努力寻找一种方法来计算将显示在最后一行不使用脚本代码,有什么建议吗?

:我试着把答案合并成一个全面的列表。我提到的名字在适当的地方给予信用的地方。



有很多方法可以解决这个问题, / p>

纯JSP解决方案

上面提到的ScArcher2是一个非常简单的解决方案问题是直接在JSP中实现它:

 < c:set var =ageTotalvalue = $ {0}/> 
< c:forEach var =personitems =$ {personList}>
< c:set var =ageTotalvalue =$ {ageTotal + person.age}/>
< tr>< td> $ {person.name}< td>< td> $ {person.age}< / td>< / tr>
< / c:forEach>
$ {ageTotal}

这个解决方案的问题是JSP变得混乱指出你可能已经引入了脚本。如果您预计每个看到该页面的人都能够遵循目前的基本逻辑,那么这是一个不错的选择。

纯粹的EL解决方案



如果您已经在EL 3.0(Java EE 7 / Servlet 3.1)上,请使用新的支持 streams和lambdas

 < c:forEach var =personitems =$ {personList}> 
< tr>< td> $ {person.name}< td>< td> $ {person.age}< / td>< / tr>
< / c:forEach>
$ {personList.stream()。map(person - > person.age).sum()}

JSP EL函数

另一种在不将脚本代码引入JSP的情况下输出总和的方法是使用EL函数。 EL函数允许您在公共类中调用公共静态方法。例如,如果您想迭代您的集合并对这些值进行求和,则可以在公共类(可能称为PersonUtils)中定义一个名为sum(List people)的公共静态方法。在你的tld文件中,你可以放置下面的声明:

 < function> 
< name> sum< / name>
< function-class> com.example.PersonUtils< / function-class>
<函数签名> int sum(java.util.List people)< / function-signature>
< / function>

在您的JSP中,您可以编写:

 <%@ taglib prefix =furi =/ your-tld-uri%> 
...
< c:out value =$ {f:sum(personList)}/>

JSP EL函数有一些好处。它们允许您使用现有的Java方法,而无需编写特定的UI(自定义标签库)。他们也是紧凑的,不会混淆非编程导向的人。
$ b

自定义标记
$ b $另一个选择是推出自己的自定义标签。这个选项将涉及最多的设置,但会给你我觉得你实际上寻找,绝对没有scriptlet。在上可以找到使用简单自定义标签的不错教程http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/JSPTags5.html#74701



涉及的步骤包括继承TagSupport :

  public PersonSumTag extends TagSupport {
$ b $ private List personList;

public List getPersonList(){
return personList;
}

public void setPersonList(List personList){
this.personList = personList;


public int doStartTag()throws JspException {
try {
int sum = 0;
for(Iterator it = personList.iterator(); it.hasNext()){
Person p =(Person)it.next();
sum + = p.getAge();

pageContext.getOut()。print(+ sum);
catch(Exception ex){
throw new JspTagException(SimpleTag:+
ex.getMessage());
}
返回SKIP_BODY;
}
public int doEndTag(){
return EVAL_PAGE;




$ p $定义tld文件中的标签:

 < tag> 
< name> personSum< / name>
< tag-class> example.PersonSumTag< / tag-class>
< body-content>空< / body-content>
...
<属性>
< name> personList< / name>
< required> true< / required>
< rtexprvalue> true< / rtexprvalue>
< type> java.util.List< / type>
< / attribute>
...
< / tag>

在JSP的顶部声明taglib:

 <%@ taglib uri =/ you-taglib-uriprefix =p%> 

并使用标记:

 < c:forEach var =personitems =$ {personList}> 
< tr>< td> $ {person.name}< td>< td> $ {person.age}< / td>< / tr>
< / c:forEach>
< p:personSum personList =$ {personList}/>

显示标记

前面提到的zmf,你也可以使用display标签,尽管你需要包含相应的库:

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?

解决方案

Note: I tried combining answers to make a comprehensive list. I mentioned names where appropriate to give credit where it is due.

There are many ways to solve this problem, with pros/cons associated with each:

Pure JSP Solution

As ScArcher2 mentioned above, a very easy and simple solution to the problem is to implement it directly in the JSP as so:

<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}

The problem with this solution is that the JSP becomes confusing to the point where you might as well have introduced scriplets. If you anticipate that everyone looking at the page will be able to follow the rudimentary logic present it is a fine choice.

Pure EL solution

If you're already on EL 3.0 (Java EE 7 / Servlet 3.1), use new support for streams and lambdas:

<c:forEach var="person" items="${personList}">
  <tr><td>${person.name}<td><td>${person.age}</td></tr>
</c:forEach>
${personList.stream().map(person -> person.age).sum()}

JSP EL Functions

Another way to output the total without introducing scriplet code into your JSP is to use an EL function. EL functions allow you to call a public static method in a public class. For example, if you would like to iterate over your collection and sum the values you could define a public static method called sum(List people) in a public class, perhaps called PersonUtils. In your tld file you would place the following declaration:

<function>
  <name>sum</name>
  <function-class>com.example.PersonUtils</function-class>
  <function-signature>int sum(java.util.List people)</function-signature>
</function> 

Within your JSP you would write:

<%@ taglib prefix="f" uri="/your-tld-uri"%>
...
<c:out value="${f:sum(personList)}"/>

JSP EL Functions have a few benefits. They allow you to use existing Java methods without the need to code to a specific UI (Custom Tag Libraries). They are also compact and will not confuse a non-programming oriented person.

Custom Tag

Yet another option is to roll your own custom tag. This option will involve the most setup but will give you what I think you are esentially looking for, absolutly no scriptlets. A nice tutorial for using simple custom tags can be found at http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/JSPTags5.html#74701

The steps involved include subclassing TagSupport:

public PersonSumTag extends TagSupport {

   private List personList;

   public List getPersonList(){
      return personList;
   }

   public void setPersonList(List personList){
      this.personList = personList;
   }

   public int doStartTag() throws JspException {
      try {
        int sum = 0;
        for(Iterator it = personList.iterator(); it.hasNext()){
          Person p = (Person)it.next();
          sum+=p.getAge();
        } 
        pageContext.getOut().print(""+sum);
      } catch (Exception ex) {
         throw new JspTagException("SimpleTag: " + 
            ex.getMessage());
      }
      return SKIP_BODY;
   }
   public int doEndTag() {
      return EVAL_PAGE;
   }
}

Define the tag in a tld file:

<tag>
   <name>personSum</name>
   <tag-class>example.PersonSumTag</tag-class>
   <body-content>empty</body-content>
   ...
   <attribute>
      <name>personList</name>
      <required>true</required>
      <rtexprvalue>true</rtexprvalue>
      <type>java.util.List</type>
   </attribute>
   ...
</tag>

Declare the taglib on the top of your JSP:

<%@ taglib uri="/you-taglib-uri" prefix="p" %>

and use the tag:

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

Display Tag

As zmf mentioned earlier, you could also use the display tag, although you will need to include the appropriate libraries:

http://displaytag.sourceforge.net/11/tut_basic.html

这篇关于计算c:forEach循环中所有数字的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆