【问题标题】:Unable to get component by id in the bean [duplicate]无法通过 bean 中的 id 获取组件 [重复]
【发布时间】:2021-09-22 06:03:26
【问题描述】:

我试着在ManagedBean做:

UIComponent a = FacesContext.getCurrentInstance().getViewRoot().findComponent("a:b");

我检查了 chrome 浏览器检查器,组件的 id 为“a:b”。但是调试代码,我得到UIComponent 等于null

我尝试了所有组合:“:a:b”、“:b”、“b”、“\\:a\\:b”...

我正在使用 Primefaces 3.4.1 和 Mojarra 2.1.7

更新:我也按照 cmets 中的建议进行了尝试:

UIComponent container = FacesContext.getCurrentInstance().getViewRoot().findComponent("a");
UIComponent b = ((UIComponentBase) container).findComponent("b");

container 不是 null,但bnull

【问题讨论】:

  • @JasperdeVries 我更新了这个问题。无论如何,您能解释一下为什么要删除 Primefaces 和 jsf 2 标签吗?
  • 这个问题与 PrimeFaces (它是纯粹的 JSF 功能)和 JSF 2.2 无关(您使用的是 2.1,它也可以应用于 2.3,所以不需要抛出这些版本) .
  • @JasperdeVries 由于我使用 Primefaces,也许有一个可以使用 Primefaces 完成的解决方案。而且由于我使用的是 jsf 2,所以 jsf 3 和 4 的解决方案是无效的。此外,人们知道我有 jsf 2 而不是旧的 JSF 1。请问我可以再放这些标签吗?
  • 请提供minimal reproducible examplea 是命名容器吗?您的(相关)xhtml 结构是什么?您何时何地调用此代码?

标签: jsf


【解决方案1】:

启发解决Abbas Gadhia's answer:

public class JsfUtil {
   public static UIComponent findComponent(String id) {
       FacesContext context = FacesContext.getCurrentInstance();
       UIComponent root = context.getViewRoot();
       UIComponent res = root.findComponent(id);
       return res;
   }
   
   public static UIComponent findSubComponent(final String id, UIComponent container) {
       FacesContext context = FacesContext.getCurrentInstance();
       
       if (container == null) {
           container = context.getViewRoot();
       }
       
       String idContainer = container.getId();
       
       if (id.equals(idContainer)) {
            return container;
        }
       
       final UIComponent[] found = new UIComponent[1];
       VisitContext visitContext = VisitContext.createVisitContext(context);
       
       container.visitTree(visitContext, new VisitCallback() {
           @Override
           public VisitResult visit(
               VisitContext context, 
               UIComponent component
           ) {
               String idComponent = component.getId();
               
               if (id.equals(idComponent)) {
                   found[0] = component;
                   return VisitResult.COMPLETE;
               }
               
               return VisitResult.ACCEPT;
           }
       });
       
       return found[0];
   }
}

用法:

UIComponent container = JsfUtil.findComponent("containerId");
UIComponent element = JsfUtil.findSubComponent("lastPartOfElementId", container);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-13
    • 2012-07-20
    • 1970-01-01
    • 2014-06-27
    • 1970-01-01
    • 2012-08-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多