如何在 JSF EL 中显示 List#size() 的值? [英] How to display value of List#size() in JSF EL?
问题描述
我想知道是否有办法将方法的返回值绑定到 JSF 组件中.我会更好地解释自己.假设我有一个这样的课程:
I'd like to know if there's a way to bind the returned value of a method into a JSF component. I'll explain myself better. Let's say I have a class like this:
public class Document {
private List<Attachment> attachments;
//getter and setter here
}
这个类通过一个注册的托管bean在名为currentDocument的属性中暴露给jsf,并以这种方式在jsf中使用
this class is exposed to jsf through a registered managed bean in a property called currentDocument, and used in a jsf this way
<h:outputText value="#{myManagedBean.currentDocument.attachment.size}" />
这不正确,我知道.但是,这样做的正确方法是什么?我应该在 Document 类上创建一个属性,比如说 numberOfAttachments,然后绑定到它,还是有一种方法可以直接绑定到方法的返回值上?
This isn't correct, I know. But what is the correct way to do this? Am I supposed to create an attribute on the Document class, let's say numberOfAttachments, and bind to that, or there's a way to bind directly on a method's return value?
推荐答案
如果您正在运行支持 EL 2.2 的容器(Tomcat 7、Glassfish 3、JBoss AS 6 或更新版本,均实现 Servlet 3.0),或者正在使用 JBossEL,那么您应该能够通过 EL 调用非 getter 方法:
If you're running an EL 2.2 capable container (Tomcat 7, Glassfish 3, JBoss AS 6 or newer, all implementing Servlet 3.0), or are using JBoss EL, then you should be able to invoke non-getter methods by EL:
<h:outputText value="#{myManagedBean.currentDocument.attachment.size()}" />
另一种方法是使用 JSTL fn:length()
:
An alternative is to use JSTL fn:length()
:
<html xmlns:fn="http://java.sun.com/jsp/jstl/functions" ...>
...
<h:outputText value="#{fn:length(myManagedBean.currentDocument.attachment)}" />
如果由于某种原因这些都不可能,那么最好的办法是自己创建一个 EL 函数
If none of that is possible for you for some reason, then your best bet is to create an EL function yourself
<h:outputText value="#{my:size(myManagedBean.currentDocument.attachment)}" />
或者向 #{myManagedBean}
添加一个额外的 getter 方法,它返回的正是那个.
or to add an extra getter method to #{myManagedBean}
which returns exactly that.
<h:outputText value="#{myManagedBean.currentDocumentAttachmentSize}" />
另见:
- 在 EL 中调用直接方法或带参数/变量/参数的方法莉>
这篇关于如何在 JSF EL 中显示 List#size() 的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!