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

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

问题描述

想象一下一个JSF页面,其中包含几个组件,例如<h:selectOneMenu><h:dataTable><h:panelGrid>等.每个组件都有一个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?

推荐答案

您可以通过

You can get the component tree by FacesContext#getViewRoot() and find a particular component by ID by 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() {
    // ...
}


无关与具体问题无关,尚不清楚为什么需要执行此操作,但我可以说这比通常的代码气味更重要.我建议研究一下这是否真的是您所想到的具体功能要求的正确解决方案.有关线索和提示,另请参见


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天全站免登陆