在页面加载时调用JSF托管的Bean操作 [英] Invoke JSF managed bean action on page load

查看:106
本文介绍了在页面加载时调用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.
}

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

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:viewParam>进行初始化,或者将bean置于比视图范围更广的范围内(这反过来又表明了设计问题,但这又是一个问题),请使用<f:event type="preRenderView">.否则,@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 +

或者,如果您也打算基于<f:viewParam>进行初始化,或者将bean放置在比视图范围更广的范围内(这反过来又说明了设计问题,但要排除这一点),请使用<f:viewAction>.否则,@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";
}

另请参见:

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆