问题
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