JSF 2 invoke action method on page load

There are several ways to automatically invoke back-end bean/action in JSF 2 on page load or when reach a specific URL. The ways that I know are :

1. using annotation @PostConstruct
If we annotate a method with @PostConstruct, it will be called at bean initialization.
   @PostConstruct
   public void init() {
      //code here
   }

2. using f:event.

   


3. using binding attribute
JSF 2 tags which have binding attibute such as h:form ,h:panelGroup, h:commandLink will invoke the method that binds to these elements.



It's important to understand the scope concept in JSF 2 to get the desired result. We might want to load the action method once and then proceed with another logic that trigger another action in the same page but end up calling this on load action method every time before invoke the real method that we want. Check the scope.

If it's request scope then it will be called each time we invoke any methods in the page since request scope only lasts for a call and the bean will be initialized again in the next call. Change it to view scope or session scope will extend the life time of the bean.

7 comments:

  1. Using binding to trigger bean function is not working. According to your sample, the application will try to call the function "getForm" in todoController. Even you've create the getForm function in the bean, the server still throw a PropertyNotFoundException.

    Any hints?

    ReplyDelete
  2. hi Ivan,
    You need to create a bogus field with its getter/setter if you are using binding. it would look like this:

    private String form;

    public String getForm() {
    //do your logic here
    return null;
    }

    public void setForm(String form) {
    this.form= form;
    }
    in order to avoid classCastException we return null in getForm method.

    ReplyDelete
  3. Welcome Lukasz, I just consider this as a note for myself, by the way, sharing is caring :D

    ReplyDelete
  4. So are these the best ways to load your datatables? Or are there any other strategies?

    ReplyDelete