Question

I'm using JSF 2.1 and Primefaces:

I have a view scoped managed bean with a managed property and a method that set something on other view scoped managed bean and forward to other page referencing that managed bean:

@ManagedBean
@ViewScoped
public class HelloMB {

   @ManagedProperty("otherMB")
   private OtherMB other;

   public String changeOtherMB() {
      otherMB.setAnyObject(new Object());
      return "otherPage.xhtml";
   }

}

@ManagedBean
@ViewScoped
public class OtherMB {

   private Object o;    

   public void setAnyObject(Object o) {
      this.o = o;
   }

}

So, when otherPage is rendered o is null.

You have idea how could I solve this? How can I retain an Object in a @ViewScoped managed bean and keep it live on other page without using @SessionScoped?

Was it helpful?

Solution

The view scope is destroyed and recreated once you navigate to a different JSF view. You know, the view scope lives as long as you're interacting with the same JSF view. In this particular case you effectively end up with two instances of the #{otherMB} managed bean during one request. One instance which is used by the source view and another instance which is used by the destination view.

As the second view is created within the very same request, you could just pass it as a request attribute.

@ManagedBean
@ViewScoped
public class HelloMB implements Serializable {

    public String changeOtherMB() {
        ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
        ec.getRequestMap().put("anyObject", anyObject);
        return "otherPage.xhtml";
    }

}
@ManagedBean
@ViewScoped
public class OtherMB {

    private Object anyObject;    

    @PostConstruct
    public void init() {
        ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
        this.anyObject = ec.getRequestMap().get("anyObject");
    }

}

I however wonder if you're aware about the importance of idempotent vs non-idempotent requests. Perhaps you actually need a "plain vanilla" link without the need to invoke a view scoped bean action method. See the last "See also" link below for an extensive example on that.

See also:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top