在JSF 2.0中检索其他组件的客户端ID

JSF 2.0是否有内置方法来查找另一个组件的客户端ID? 在SO上有大约一千个与客户端ID相关的问题,并且有很多hackish方法可以做到这一点,但我想知道JSF 2.0是否带来了一个我不知道的更简单的方法。

#{component.clientId}计算给定组件自己的客户端ID,但我想引用另一个组件的ID。

这篇博文提到了component.clientId ,它也说#{someComponent.clientId}可以工作,但是我可以告诉它没有。 我相信他在JSF 2.0的任何参考实现出来之前都写过,所以他只是去了JSR,也许这个function发生了变化。 我不确定。

我知道PrimeFaces和RichFaces都有自己的函数来返回客户端ID,但我只是想知道是否有内置的JSF 2.0方法。 这里有些例子:

这可以返回outputText的ID。

 `` 

根据上面的博客文章,这应该有效,但事实并非如此。 我没有输出。

 `` `` 

这适用于PrimeFaces:

 `` 

在RichFaces中工作:

 `` 

此外,如果我可能的话,我正在寻找不会破坏的解决方案,如果我更改javax.faces.SEPARATOR_CHAR值或者我在引用的组件之外添加/删除容器。 我花了很多时间来追踪由硬编码ID路径引起的问题。

您需要通过binding属性在视图范围中为组件分配变量名称。

   

这对我有用。 我很想知道写这样的回答是否可以。

client.html

  

UIHelper.java

 @ManagedBean(name = "UIHelper", eager = true) @ApplicationScoped public class UIHelper { public String clientId(final String id) { FacesContext context = FacesContext.getCurrentInstance(); UIViewRoot root = context.getViewRoot(); final UIComponent[] found = new UIComponent[1]; root.visitTree(new FullVisitContext(context), new VisitCallback() { @Override public VisitResult visit(VisitContext context, UIComponent component) { if (component.getId().equals(id)) { found[0] = component; return VisitResult.COMPLETE; } return VisitResult.ACCEPT; } }); return found[0] == null ? "" : "#" + found[0].getClientId().replace(":", "\\\\:"); } } 

由于这是我的谷歌搜索的第一个结果之一,我想知道为什么我有一个

javax.el.PropertyNotFoundException(未找到属性’itemId'[…])

在尝试接受的解决方案时,我想分享我的JSF 1.2解决方案:

UIComponent的方法getClientId需要一个FacesContext参数(参见UIComponent文档 )。 因此,添加绑定到支持bean以及另一个返回clientId的方法:

XHTML:

   

豆:

 private UIComponent sampleButton; public UIComponent getSampleButton() { return sampleButton; } public void setSampleButton(final UIComponent sampleButton) { this.sampleButton = sampleButton; } public String getSampleButtonClientId() { final FacesContext context = FacesContext.getCurrentInstance(); return sampleButton.getClientId(context); } 

请注意,您绑定组件的bean应该是请求范围的,否则您最终可能会遇到java.lang.IllegalStateException (duplicate Id for a component) (与此主题相比 )。