Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSF bean: call @PostConstruct function after ViewParam is set

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?

like image 784
user579674 Avatar asked Apr 21 '12 17:04

user579674


1 Answers

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
like image 182
BalusC Avatar answered Oct 15 '22 11:10

BalusC