How to start special init event in a backing bean before JSF page loads?

僤鯓⒐⒋嵵緔 提交于 2021-02-07 04:04:38

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/18490841/how-to-start-special-init-event-in-a-backing-bean-before-jsf-page-loads

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