jsf - 无法通过 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
不是,而是_ null
b
null
解决方案
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);
推荐阅读
- amazon-web-services - 当 ebs 卷崩溃时,如何使 EBS 卷以零停机时间可用并附加到 EC2 实例?
- reactjs - 在 github 用户页面上部署 React 投资组合网站
- prolog - Prolog 尝试打印但出错
- javascript - 如何在 Javascript 中动态验证电子邮件域
- piranha-cms - Piranha CMS - 添加自定义身份验证的问题
- python - 如何使用 python 在无头模式下运行 chrome 驱动程序?
- python - 使用蒙特卡洛在 (0≤≤1,0≤≤1) 范围内的至少两个圆的相交区域
- javascript - 是否可以一次更改包含相同日期的所有日期字段?
- android - 由 android.database.CursorWindowAllocationException 引起
- c# - 如何使用 gmail api 获取带有消息详细信息的参考和回复