Question

When the page loads for the first time, the @PostConstruct is called, but when I perform a postback on this page, the @PostConstruct is called again.

How can I make it to run only on the initial request and not on every postback?

@PostContruct
public void init() {
    // charge combos....
}

public void submit() { 
    // action 
}
Was it helpful?

Solution

Apparently your bean is request scoped and thus reconstructed on every HTTP request. I'm not exactly sure why you'd like to prevent the @PostConstruct from being called again, as you would otherwise end up with an "empty" bean state which might possibly lead to form submit errors, but okay, you could add a check if the current request is not a postback.

public void init() {
    if (!FacesContext.getCurrentInstance().isPostback()) {
        // charge combos....
    }
}

This way the "charge combos" part won't be invoked on postbacks.

Or, maybe your actual question is not "How to prevent postconstruct from being called on postback?", but more "How to retain the same bean instance on postback?". In that case, you'd need to put the bean in the view scope instead of in the request scope.

@ManagedBean
@ViewScoped
public class Bean implements Serializable {
    // ...
}

As long as you return null from action methods, this way the same bean instance will live as long as you're interacting with the same view by postbacks. This way the @PostConstruct won't be invoked (simply because the bean isn't been reconstructed).

See also:

OTHER TIPS

use this import:

import javax.faces.view.ViewScoped; for @ViewScoped

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top