Dynamic value binding of JSF component

后端 未结 2 1320
终归单人心
终归单人心 2020-12-20 23:13

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



        
相关标签:
2条回答
  • 2020-12-21 00:02

    Another option is you can add a layer of abstraction to your bean.

    public String getDynamicProp() {
       ...Code to determine and return the correct property based on the meta-data...
    }
    
    public void setDynamicProp(String input) {
       ...Code to determine and return the correct property based on the meta-data...
    }
    

    Then you would tie your JSF directly to the dynamic prop:

    #{bean.dynamicProp}
    

    However, this won't hang on to the metadata like validators and the like you were wanting. However, you can programatically invoke validation and handle it yourself.

    0 讨论(0)
  • 2020-12-21 00:20

    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.

    0 讨论(0)
提交回复
热议问题