Invoke JSF managed bean action on page load

前端 未结 4 2228
别跟我提以往
别跟我提以往 2020-11-22 13:16

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

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

4条回答
  •  南笙
    南笙 (楼主)
    2020-11-22 13:50

    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

    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.
    }
    

    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.

    JSF 2.0 / 2.1

    Alternatively, use in case you intend to initialize based on 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.

    
        
        
    
    
    public void onload() { 
        // Do your stuff here.
    }
    

    JSF 2.2+

    Alternatively, use in case you intend to initialize based on 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.

    
        
        
    
    
    public void onload() { 
        // Do your stuff here.
    }
    

    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";
    }
    

    See also:

    • How do I process GET query string URL parameters in backing bean on page load?
    • What can , and be used for?
    • How to invoke a JSF managed bean on a HTML DOM event using native JavaScript? - in case you're actually interested in executing a bean action method during HTML DOM load event, not during page load.

提交回复
热议问题