2
votes

I'm currently learning about JSF 2.0 and i dont know how to initialize something in my CDI bean everytime a jsf page is accessed ?

For example, let's say in my case, i have one CDI bean that is used in one JSF page. Somewhere inside the bean, i would like to query and initialize something, or check authorization everytime the page is accessed (not everytime the action method is called).

I could put it into the bean's constructor, but that doesnt guarantee that the constructor would be called for every calls of the jsf page ? Or should i call using the #{myBean.initialize()} on the JSF page ?

Regards, Albert Kam

3

3 Answers

2
votes

If you declare the managed bean @RequestScoped, then it will be created for every HTTP request (yes, that's "everytime a JSF page is accessed" as you say in enduser's terms). You can just do the initialization job in the bean's constructor or @PostConstruct method. This has nothing to do with CDI.

check authorization everytime the page is accessed (not everytime the action method is called).

For that, a javax.servlet.Filter or very maybe a javax.faces.event.PhaseListener is a much better solution.

0
votes

If I am not mistaken, the constructor is called every time the page loads - as soon as you apply your bean to the jsf page, that object is constructed. Hence, must have a constructor without any parameters