JSF bean: call @PostConstruct function after ViewParam is set

烂漫一生 提交于 2019-11-27 21:45:43

问题


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?

UPDATE

I found what was wrong. I think the viewParam method works with CDI beans but the ManagedProperty method works with JSF beans..

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?


回答1:


You need a <f:event type="preRenderView"> instead.

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

With

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

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>

See also:

  • ViewParam vs @ManagedProperty(value = "#{param.id}")
  • Communication in JSF 2.0 - Processing GET request parameters


来源:https://stackoverflow.com/questions/10261453/jsf-bean-call-postconstruct-function-after-viewparam-is-set

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!