JSF bean:在设置 ViewParam 后调用 @PostConstruct 函数 [英] JSF bean: call @PostConstruct function after ViewParam is set
问题描述
我有一个 product.xhtml 和一个 ProductBean.我使用/product/{id} 来访问产品,所以我在 product.xhtml 中有一个 viewParam 值=ProductBean.id.问题是在 bean 内部我使用了一个带有 PostConstruct 注释的 init 函数来填充产品的细节.为此,我需要 id 来调用外部函数.我猜虽然 init 在 viewParam 设置 bean 的 id 之前被调用,因此在 init 内部我不能调用外部函数,因为 id 尚未设置.我做错了什么,我该如何解决?
I have a product.xhtml and a ProductBean. I use /product/{id} to access the products so I have a viewParam in product.xhtml with value=ProductBean.id. The problem is that inside the bean I use an init function with a PostConstruct annotation in order to fill the details of the product. To do this I need the id to call an external function. I guess though that init is called before viewParam sets the id of the bean and therefore inside init I cannot call the external function because id is not set yet. What am I doing wrong and how do I fix this?
更新
我发现出了什么问题.我认为 viewParam 方法适用于 CDI bean,但 ManagedProperty 方法适用于 JSF beans..
I found what was wrong. I think the viewParam method works with CDI beans but the ManagedProperty method works with JSF beans..
我现在还有一个问题.我的 CDI bean 是 RequestScoped 并且当 product.xhtml 呈现时,bean 被创建,我猜后来被丢弃了.有趣的是,我在那个 bean 中有一个函数,当我调用它时,我可以读取 id(我认为这是因为连接到视图参数),但不能读取任何其他属性.任何想法如何解决这个问题?
I do have one other problem now. My CDI bean is RequestScoped and when the product.xhtml is rendered the bean is created and I guess is later discarded. The funny thing is that I have a function inside that bean which when I call, I can read the id (which I assume this happens because is connected to the view param) but not any other properties. Any ideas how to fix this?
推荐答案
你需要一个
代替.
<f:metadata>
<f:viewParam name="foo" value="#{bean.foo}" />
<f:event type="preRenderView" listener="#{bean.onload}" />
</f:metadata>
与
public void onload() {
// ...
}
请注意,这本质上是一个小技巧.即将推出的 JSF 2.2 将提供一个新的、更合理的标签,用于唯一目的:
.
Note that this is in essence a little hack. The upcoming JSF 2.2 will offer a new and more sensible tag for the sole purpose: the <f:viewAction>
.
<f:metadata>
<f:viewParam name="foo" value="#{bean.foo}" />
<f:viewAction action="#{bean.onload}" />
</f:metadata>
另见:
- ViewParam vs @ManagedProperty(value = "#{param.id}")
- JSF 2.0 中的通信 - 处理 GET 请求参数
这篇关于JSF bean:在设置 ViewParam 后调用 @PostConstruct 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!