JSF bean:设置ViewParam后,调用@PostConstruct函数 [英] JSF bean: call @PostConstruct function after ViewParam is set

查看:185
本文介绍了JSF bean:设置ViewParam后,调用@PostConstruct函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个product.xhtml和一个ProductBean.我使用/product/{id}来访问产品,所以我在product.xhtml中有一个viewParam,其值为value = 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 bean.

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(我认为发生这种情况是因为它已连接到view param),但没有其他任何属性.有任何解决方法的想法吗?

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:event type="preRenderView">.

<f:metadata>
    <f:viewParam name="foo" value="#{bean.foo}" />
    <f:event type="preRenderView" listener="#{bean.onload}" />
</f:metadata>

使用

public void onload() {
    // ...
}

请注意,这本质上是一个小技巧.即将发布的JSF 2.2将提供一个新的且更明智的标记,用于唯一目的:<f:viewAction>.

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>

另请参见:

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆