I need to use some data saved in a view scoped bean in an other view scoped bean.
@ManagedBean
@ViewScoped
public class Attivita implements Serializable {
//
}
and
@ManagedBean
@ViewScoped
public class Nota implements Serializable {
@ManagedProperty("#{attivita}")
private Attivita attivita;
// Getter and setter.
}
Now, maybe my theory about it is still quite poor, I have noticed that when #{attivita}
is injected, the Attivita
constructor is invoked and thus creating another instance. Is it the right behaviour? What about if I want to reference the same instance and not create a new one?
This will happen if you're navigating from one to the other view on a postback. A view scoped bean is not tied to a request, but to a view. So when you navigate to a new view, it will get a brand new instance of the view scoped bean. It won't reuse the same bean instance which is associated with a previous view.
I understand that the
attivita
bean is created on the initial view and reused on postback. I understand thatnota
bean is associated with the new view where you're navigating to. When injectingattivita
in it, it will simply get a new and distinct instance even though there's another instance in the very same request. This is all expected (and admittedly a bit unintuitive) behaviour.There is no standard JSF solution for this. CDI solves this with
@ConversationScoped
(the bean lives as long as you explicitly tell it to live) and the CDI extension MyFaces CODI goes a bit further with@ViewAccessScoped
(the bean lives as long as the navigated view references it).You could however workaround this by storing the bean as an attribute in the request scope.
and
Note that this is rather hacky. There may be better solutions depending on the concrete functional requirement. Also note that you should in the
nota
view reference the desiredAttivita
bean instance as#{nota.attivita}
and not as#{attivita}
, because it would give you a new and different instance, for the reasons already explained before.Your
attivita
bean is@ViewScoped
and that doesn't guarantee that your instance will be hold in session. You need a@SessionScoped
bean. However, if you needattivita
for some reason to be@ViewScoped
, then you can pass params through them in other ways, e.g. usingviewParam
or using other@SessionScoped
bean between them.Page Params
http://mkblog.exadel.com/2010/07/learning-jsf2-page-params-and-page-actions/
JSF 2 Managed Bean Scopes
http://balusc.blogspot.com.es/2011/09/communication-in-jsf-20.html#ManagedBeanScopes