首页 > 解决方案 > 无法通过 bean 中的 id 获取组件

问题描述

我试图在一个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

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

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

container不是,而是_ nullbnull

标签: jsf

解决方案


解决了阿巴斯·加迪亚(Abbas Gadhia)的回答

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);

推荐阅读