java 在 JSP 页面中获取 List.size() 的值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34009525/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 22:24:16  来源:igfitidea点击:

get the value of a List.size() in a JSP page?

javajsp

提问by user1071914

This is a simple question, I should know the answer and I'm ashamed to admit I don't. I am sending a compound object to my JSP page:

这是一个简单的问题,我应该知道答案,但我很惭愧地承认我不知道。我正在向我的 JSP 页面发送一个复合对象:

public class MyObject {
    private List<MyFoo> myFoo;
    public getMyFoo();
    public setMyFoo();
}

// In the controller...
model.addAttribute("myObject", myObject);

When this goes into the JSP page I can address the model instance of myObject as:

当它进入 JSP 页面时,我可以将 myObject 的模型实例寻址为:

${myObject}

and the list inside as

和里面的列表作为

${myObject.myFoo}

What I wantto do is list the size of myFoo on my JSP output, like so:

想要做的是在我的 JSP 输出中列出 myFoo 的大小,如下所示:

${myObject.myFoo.size}

But of course size() is not a bean property, so a JSPException is thrown.

但是当然 size() 不是 bean 属性,因此会抛出 JSPException。

Is there a simple, elegant way of doing this in the JSP page or do I need to stick another attribute on the model and put the size in there?

在 JSP 页面中是否有一种简单、优雅的方法来执行此操作,或者我是否需要在模型上粘贴另一个属性并将大小放在那里?

回答by Matteo Di Napoli

You could use JSTL tag libraries, they are often useful for common JSP operations. Here's a quick reference: https://code.google.com/p/dlcode/downloads/detail?name=jstl-quick-reference.pdf

您可以使用 JSTL 标记库,它们通常对常见的 JSP 操作很有用。这是一个快速参考:https: //code.google.com/p/dlcode/downloads/detail?name=jstl-quick-reference.pdf

Include the taglib with this line:

在这一行中包含 taglib:

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

Then your case would be:

那么你的情况是:

${fn:length(myObject.myFoo)}

回答by Tsung-Ting Kuo

One plausible (but may not be elegant enough) way is to add a getter function:

一种合理(但可能不够优雅)的方法是添加一个 getter 函数:

public getMyFooSize() { return myFoo.size(); }

And then use the following in JSP:

然后在 JSP 中使用以下内容:

${myObject.myFooSize}