Arian
Arian

Reputation: 3241

Managed Bean - Only execute code on page load

I'm curious about how to get JSF to only load certain business logic on page load and not run this code when I click a button (ActionEvent) or execute an AjaxBehaviorEvent.

My bean is in @RequestScoped, using JSF 2.1 and Primefaces.

Because the ActionEvent and AjaxBehaviorEvent are called afterwards I don't know how to tell the Bean in @PostConstruct that it is called because of the events.

Is it because of the bean placed in wrong scope?

Upvotes: 3

Views: 1382

Answers (2)

BalusC
BalusC

Reputation: 1108712

Only execute code on page load GET request

Just check in (post)constructor if FacesContext#isPostback() returns false.

@PostConstruct
public void init() {
    if (!FacesContext.getCurrentInstance().isPostback()) {
        // ...
    }
}

In the upcoming JSF 2.2 you can by the way use the new <f:viewAction> for this instead.

<f:viewAction action="#{bean.init}" onPostback="false" />

Is it because of the bean placed in wrong scope?

Depends on the concrete functional requirements. See also How to choose the right bean scope?


I got serious problems with ViewScoped. It always needs a serialized class which I find anoying ;) - additionally it causes sligth problems with 'java.sql'

This indicates a problem with your own code design rather than with the view scope. JDBC code doesn't belong in a JSF managed bean. JDBC resources like Connection, etc should never, never be declared as instance variables.

Upvotes: 7

Ozan Tabak
Ozan Tabak

Reputation: 672

A RequestScoped bean is re-created on each request sent from client to server, that's why the logic in @PostConstruct is executed everytime you click a button, i think you should use a ViewScoped bean instead, which is created on each page load.

You can find a good tutorial about this subject written by BalusC on this link: http://balusc.blogspot.com/2011/09/communication-in-jsf-20.html#ManagedBeanScopes

Upvotes: 1

Related Questions