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.
Just put the desired logic in the constructor of the request scoped bean associated with the JSF page.
public Bean() { // Do your stuff here. }
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.
Alternatively, use <f:event type="preRenderView">
in case you intend to initialize based on <f:viewParam>
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.
<f:metadata> <f:viewParam name="foo" value="#{bean.foo}" /> <f:event type="preRenderView" listener="#{bean.onload}" /> </f:metadata>
public void onload() { // Do your stuff here. }
Alternatively, use <f:viewAction>
in case you intend to initialize based on <f:viewParam>
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.
<f:metadata> <f:viewParam name="foo" value="#{bean.foo}" /> <f:viewAction action="#{bean.onload}" /> </f:metadata>
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"; }
load
event, not during page load.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With