3

PF 3.5.10, Mojarra 2.1.21, Omnifaces 1.5

How to call special init()-method of some (CDI)SessionScoped bean before I load a .xhtml JSF page ? Now I call init() if user select the page from site menu (with p:menutitem). But what to do if the user use browser address line to type url directly?

Edit: my.xhtml:

<ui:define template="/mytemp.xhtml">
   <f:event type="preRenderView" listener="#{mybean.init()}" />
   <h:form>
     <p:commandButton update="@form" ... />
   </h:form>
</ui:define>

If I do it that way the init() will be called on every update (i.e. on every postback to a server),in example on every click of commandButton. So I can not use your proposal.

Edit 2: Thank you Luiggi Mendoza, and BalusC! In addtion to solution from Luiggi Mendoza, as in comments stated the Omnifaces 1.6 will be have ViewScope also.

Tony
  • 2,266
  • 4
  • 33
  • 54

1 Answers1

10

The problem is that the @PostConstruct public void init() method is called after the managed bean is created and the fields are injected. Since your bean is @SessionScoped, it will live until the user session expires.

A way to solve is to use <f:event type="preRenderView" listener="{bean.init}" /> as explained here: What can <f:metadata>, <f:viewParam> and <f:viewAction> be used for? (no need to use <f:metadata> as explained by BalusC here: Does it matter whether place f:event inside f:metadata or not?).

Per your question update, this problem is handled in the first link. I'll post the relevant code to handle this situation (taken from BalusC answer):

public void init() {
    FacesContext facesContext = FacesContext.getCurrentInstance();
    if (!facesContext.isPostback() && !facesContext.isValidationFailed()) {
        // ...
    }
}

If you migrate to JSF 2.2, then there's a @ViewScoped annotation for CDI beans and you could reduce the scope of your @SessionScoped beans accordingly.

Community
  • 1
  • 1
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332