Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
958 views
in Technique[技术] by (71.8m points)

jsf 2 - Programmatically getting UIComponents of a JSF view in bean's constructor

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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");
// ...

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}" />

with

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...