本文介绍了在页面加载时调用 JSF 托管 bean 操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在页面加载时执行 JSF 托管 bean 操作?

Is there a way to execute a JSF managed bean action when a page is loaded?

如果相关,我目前使用的是 JSF 1.2.

If that's relevant, I'm currently using JSF 1.2.

推荐答案

JSF 1.0/1.1

只需将所需的逻辑放在与 JSF 页面关联的请求范围 bean 的构造函数中.

JSF 1.0 / 1.1

Just put the desired logic in the constructor of the request scoped bean associated with the JSF page.

public Bean() {
    // Do your stuff here.
}

JSF 1.2/2.x

在请求或视图范围的 bean 上使用 @PostConstruct 注释方法.它将在所有托管属性和注入的依赖项的构造初始化/设置后执行.

JSF 1.2 / 2.x

Use @PostConstruct annotated method on a request or view scoped bean. It will be executed after construction and initialization/setting of all managed properties and injected dependencies.

@PostConstruct
public void init() {
    // Do your stuff here.
}

如果您使用的是使用代理的 bean 管理框架(例如 CDI),强烈建议使用此方法而不是构造函数,因为可能不会在您期望的时间调用构造函数.

This is strongly recommended over constructor in case you're using a bean management framework which uses proxies, such as CDI, because the constructor may not be called at the times you'd expect it.

或者,使用 <f:event type="preRenderView"> 如果您也打算基于 进行初始化,或者当bean 被置于比视图范围更广的范围内(这反过来表明设计问题,但除此之外).否则,@PostConstruct 也完全没问题.

Alternatively, use <f:event type="preRenderView"> in case you intend to initialize based on <f:viewParam> too, or when the bean is put in a broader scope than the view scope (which in turn indicates a design problem, but that aside). Otherwise, a @PostConstruct is perfectly fine too.

<f:metadata>
    <f:viewParam name="foo" value="#{bean.foo}" />
    <f:event type="preRenderView" listener="#{bean.onload}" />
</f:metadata>
public void onload() {
    // Do your stuff here.
}

JSF 2.2+

或者,如果您也打算基于 进行初始化,或者当 bean 被放入一个比视图范围更广的范围(这反过来表明设计问题,但除此之外).否则,@PostConstruct 也完全没问题.

JSF 2.2+

Alternatively, use <f:viewAction> in case you intend to initialize based on <f:viewParam> too, or when the bean is put in a broader scope than the view scope (which in turn indicates a design problem, but that aside). Otherwise, a @PostConstruct is perfectly fine too.

<f:metadata>
    <f:viewParam name="foo" value="#{bean.foo}" />
    <f:viewAction action="#{bean.onload}" />
</f:metadata>
public void onload() {
    // Do your stuff here.
}

请注意,如有必要,这可以返回 String 导航案例.它将被解释为重定向(因此您不需要 ?faces-redirect=true 此处).

Note that this can return a String navigation case if necessary. It will be interpreted as a redirect (so you do not need a ?faces-redirect=true here).

public String onload() {
    // Do your stuff here.
    // ...
    return "some.xhtml";
}

另见:

08-01 05:42