java JSF 组件的动态值绑定

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2226122/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 20:09:13  来源:igfitidea点击:

Dynamic value binding of JSF component

javajsfrichfaces

提问by bungrudi

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.

就我而言,“#{bean.someProp}”仅在运行时已知。

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?

我应该遍历组件树并以编程方式设置值绑定吗?如果是,我应该在哪个 JSF 生命周期阶段进行遍历?

回答by BalusC

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

您可以将它绑定到一个Map<String, Object>bean 属性,其中String键小于或大于动态属性名称。您可以通过以下方式访问 EL 中的地图值:

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

or

或者

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

which can even be done a tad more dynamically where someVaractually resolves to a Stringvalue of "someProp":

这甚至可以在someVar实际解析为以下String值的情况下更动态地完成"someProp"

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

You only need to ensure that the Mapis 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:

您只需要确保Map在 bean 初始化期间创建,否则 JSF 无法访问映射值。EL 即不会为您预先创建“嵌套属性”。因此,做例如直接实例化:

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

.. or inside a Constructor or @PostConstructif you like.

.. 或者在构造函数中或者@PostConstruct如果你喜欢。

回答by Drew

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

另一种选择是您可以向 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:

然后你可以将你的 JSF 直接绑定到动态道具:

#{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.

但是,这不会保留在元数据上,例如验证器等您想要的东西。但是,您可以以编程方式调用验证并自行处理。