Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent @PostConstruct from being called on postback

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 
}
like image 881
Dante Panella Avatar asked Nov 06 '12 13:11

Dante Panella


1 Answers

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:

  • How to choose the right bean scope?
like image 123
BalusC Avatar answered Oct 07 '22 11:10

BalusC