在 bean 的构造函数中以编程方式获取 JSF 视图的 UIComponents [英] Programmatically getting UIComponents of a JSF view in bean's constructor

查看:11
本文介绍了在 bean 的构造函数中以编程方式获取 JSF 视图的 UIComponents的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象一个包含多个组件的 JSF 页面,例如 等.每个组件都有一个 ID.是否有任何方法或技术可以在调用 bean 的构造函数时以编程方式获取组件?

Imagine a JSF page with several components such as <h:selectOneMenu>, <h:dataTable>, <h:panelGrid>, etc. Each component has an ID. Is there any method or technique by which I can get the components programmatically when the constructor of the bean is invoked?

推荐答案

可以通过 FacesContext#getViewRoot() 并通过 UIComponentBase#findComponent():

UIViewRoot viewRoot = FacesContext.getCurrentInstance().getViewRoot();
UIComponent component = viewRoot.findComponent("someId");
// ...

然而,视图根不能直接在 bean 的构造函数中使用.它可能会在对视图的 GET 请求时返回 null,其中视图构建时间标记或属性中未引用 bean.然而,它保证在预渲染视图事件期间可用.

However, the view root is not directly available in the bean's constructor per se. It might return null on GET requests to a view wherein the bean is not referenced in a view build time tag or attribute. It's however guaranteed to be available during the pre render view event.

<f:event type="preRenderView" listener="#{bean.init}" />

public void init() {
    // ...
}

<小时>

与具体问题无关,不清楚为什么需要这样做,但我可以看出这通常是代码异味.我建议调查这是否真的是您想到的具体功能需求的正确解决方案.有关线索和提示,另请参见 绑定"属性在 JSF 中是如何工作的?何时以及如何使用它?如何在 JSF 中使用组件绑定对吗?(会话作用域 bean 中的请求作用域组件).


Unrelated to the concrete problem, it's not clear why you need to do this, but I can tell that this is more than often a code smell. I suggest to investigate if this is really the right solution for the concrete functional requirement you've had in mind. For clues and hints, see also How does the 'binding' attribute work in JSF? When and how should it be used? and How to use component binding in JSF right ? (request-scoped component in session scoped bean).

这篇关于在 bean 的构造函数中以编程方式获取 JSF 视图的 UIComponents的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆