Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

How do I bind a value of certain component dynamically at runtime? For example, I have the following component tag,

<h:inputText value="#{bean.someProp}" />

In my case, "#{bean.someProp}" is only known at runtime.

What's the best strategy to implement this?

Should I traverse the component tree and set the value binding programmatically? If yes, at which JSF lifecycle phase should I do the traversing?

See Question&Answers more detail:os

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

1 Answer

You can bind it to a Map<String, Object> bean property where the String key is less or more the dynamic property name. You can access map values in EL the following way:

<h:inputText value="#{bean.map.someProp}" />

or

<h:inputText value="#{bean.map['someProp']}" />

which can even be done a tad more dynamically where someVar actually resolves to a String value of "someProp":

<h:inputText value="#{bean.map[someVar]}" />

You only need to ensure that the Map is created during bean initialization, otherwise JSF can't access the map values. EL namely won't precreate "nested properties" for you. Thus, do e.g. direct instantiation:

public class Bean {
    private Map<String, Object> map = new HashMap<String, Object>();
}

.. or inside a Constructor or @PostConstruct if you like.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...