如何在加载JSF页面之前在后备bean中启动特殊的init事件? [英] How to start special init event in a backing bean before JSF page loads?
问题描述
PF 3.5.10,Mojarra 2.1.21,Omnifaces 1.5
PF 3.5.10, Mojarra 2.1.21, Omnifaces 1.5
在加载.xhtml JSF页面之前,如何调用某些(CDI)SessionScoped bean的特殊init()方法?现在,如果用户从站点菜单中选择页面(使用p:menutitem
),我将调用init().但是,如果用户使用浏览器地址行直接输入url怎么办?
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?
my.xhtml
:
<ui:define template="/mytemp.xhtml">
<f:event type="preRenderView" listener="#{mybean.init()}" />
<h:form>
<p:commandButton update="@form" ... />
</h:form>
</ui:define>
如果我这样做的话,在每次更新时(即在每次回发到服务器时)都会调用init(),例如在每次单击CommandButton时都会调用init().所以我不能使用你的建议.
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.
谢谢Luiggi Mendoza和BalusC! 除了来自Luiggi Mendoza的解决方案外,如评论中所述,Omnifaces 1.6也将具有ViewScope.
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.
推荐答案
问题是在创建托管bean和注入字段之后调用@PostConstruct public void init()
方法.由于您的bean是@SessionScoped
,它将一直存在直到用户会话过期为止.
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.
一种解决方法是按照以下说明使用<f:event type="preRenderView" listener="{bean.init}" />
:什么可以< f:metadata> ;,< f: viewParam>和< f:viewAction> 用于?(不需要使用BalusC在此处解释的<f:metadata>
:是否放置f:event是否重要是否在f:metadata内部?).
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?).
根据您的问题更新,此问题将在第一个链接中处理.我将发布相关代码来处理这种情况(摘自BalusC答案):
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()) {
// ...
}
}
如果您迁移到JSF 2.2,则有一个CDI bean的@ViewScoped
注释,您可以相应地缩小@SessionScoped
bean的范围.
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.
这篇关于如何在加载JSF页面之前在后备bean中启动特殊的init事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!