在 JSF 2.0 中检索其他组件的客户机标识

2022-09-02 12:15:18

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

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

这篇博客文章提到了,它也说有效,但据我所知它没有。我相信他在JSF 2.0的任何参考实现出来之前就写过,所以他只是通过JSR,也许这个功能改变了。我不确定。component.clientId#{someComponent.clientId}

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

这用于返回输出文本的 ID。

`<h:outputText value="My client ID : #{component.clientId}" />`

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

`<h:button id="sampleButton" value="Sample" />`

`<h:outputText value="sampleButton's client ID : #{sampleButton.clientId}" />`

这在PrimeFaces中有效:

`<h:outputText value="PrimeFaces : sampleButton's client ID : #{p:component('sampleButton')}" />` 

在RichFaces中工作:

`<h:outputText value="RichFaces : sampleButton's client ID : #{rich:clientId('sampleButton')}" />`

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


答案 1

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

<h:button id="sampleButton" binding="#{sampleButton}" value="Sample" />
<h:outputText value="sampleButton's client ID : #{sampleButton.clientId}" />

答案 2

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

客户端.html

<h:outputText value="#{UIHelper.clientId('look-up-address-panel-id')}" />

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(":", "\\\\:");
}

}

推荐