Managed Bean - Only execute code on page load
java, javabeans, jsf, jsf-2, primefaces
Solution
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.
Problem
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?