问题描述
实际上可以在JSF中的托管组件之间传递任何数据吗?如果是,该如何实现?
Is it actually possible to pass any data between managed components in JSF? If yes, how to achieve this?
任何人都可以提供样品吗?
Could anyone provide any sample?
推荐答案
有几种方法.如果托管bean相互关联,则最干净的方法将是托管属性注入.假设Bean1具有与Bean2相同的范围或更大的范围.首先给Bean2一个Bean1属性:
There are several ways. If the managed beans are related to each other, cleanest way would be managed property injection. Let assume that Bean1 has the same scope or a broader scope than Bean2. First give Bean2 a Bean1 property:
public class Bean2 {
private Bean1 bean1; // +getter +setter.
}
然后将faces-config.xml
中的Bean1声明为Bean2的托管属性:
Then declare Bean1 in faces-config.xml
to be a managed property of Bean2:
<managed-bean>
<managed-bean-name>bean1</managed-bean-name>
<managed-bean-class>com.example.Bean1</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>
<managed-bean>
<managed-bean-name>bean2</managed-bean-name>
<managed-bean-class>com.example.Bean2</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
<managed-property>
<property-name>bean1</property-name>
<value>#{bean1}</value>
</managed-property>
</managed-bean>
通过这种方式,bean2
实例可以立即访问bean1
实例.
This way the bean2
instance has instant access to the bean1
instance.
如果由于某些原因不想使用托管属性注入,那么还可以获取 Application#evaluateExpressionGet()
进行编程访问.这是在Bean2中检索Bean1的示例:
If you don't want to use managed property injection for some reasons, then you can also grab Application#evaluateExpressionGet()
to access it programmatically. Here's an example of retrieving Bean1 inside Bean2:
FacesContext context = FacesContext.getCurrentInstance();
Bean1 bean1 = (Bean1) context.getApplication().evaluateExpressionGet(context, "#{bean1}", Bean1.class);
但是,必须已在faces-config.xml
中将Bean1声明为托管Bean bean1
.
The Bean1 must however already be declared as managed bean bean1
in faces-config.xml
.
有关在JSF内部传递数据的更多信息和提示,您可能会发现这篇文章有用.
For more info and hints about passing data around inside JSF, you may find this article useful.
这篇关于在JSF中的托管组件之间传递数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!