Search code examples
jsfjsf-2

Why does returning empty string from action method not recreate view?


I have a JSF page with a form that contains multiple textfields (p:inputtext) and a submit button. The page is backed by a ViewScoped backing bean. When the submit button is hit, an action method is called that returns an empty String ("").

According to this answer of BalusC, returning an empty string will refresh the view and recreate the ViewScoped backing bean.

However, when I submit my filled out form, the reloaded page still retains all my text input. How is this possible? Shouldn't the form be empty since the backing bean and view have been recreated?


Solution

  • @dmatob is right. When you have a JSF page backed by a ViewScoped bean:

    • If the method returns null, the bean won't be recreated (the values stay the same) but the page is reloaded.
    • If the method returns the same or another page, the bean will be recreated (it resets the values) and the page is reloaded.

    I was facing the same few hours ago: trying to reset the values when the method is successfully executed. So after reading around and around, I found something that finally worked out:

    You have to use action instead of actionListener (Differences here)

    <p:commandButton value="Save" action="#{backingBean.save()}" />
    

    So the method must return a String

    public String save(){
      if(validations==true){
         return "currentpage.xhtml?faces-redirect=true";
      }
      return null;
    }
    

    When everything is okay, it will recreate the bean, refresh the page and reset the values. Otherwise the method returns null so it will refresh the page but the bean.


    [EDITED]

    If the method is returning null or empty String, the bean isn't recreated: the PostConstruct (init event) isn't being triggered, so that means the values stay the same. On the other case, if it returns a String (redirecting to some page), the init event is called so the values are initialized.

    The JSF page is reloaded in both cases: when returning null/empty String or not.


    Hope it helps you... Let me know ;-)