0
votes

I have a problem with opening a sessionScoped managed bean from another. I have a page that has a table wich contains list of objects. On row click I am navigating to another page and displaying its contents. I am sending the clicked row in sessionMap object or by Flash. The object is sent and read in the other page and data are displayed. In the other page I am receiving the sessionMap or Flash in the @PostConstruct method.

If I get back and opened another object the first object will open and the problem is that its a sessionScoped bean so on the second opened it will not invoke the @PostConstruct. So what is the solution for forcing the sessionScoped to read the new value and open another session? Or how can I read an object by listener rather than @PostConstruct?

page1.java

@ManagedBean
@SessionScoped
class pageBean{

    MyObject myObj;
    public String save(){FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put(myObj,"obj");
    }
}

@ManagedBean
@SessionScoped
class pageBean{
@PostConstruct
public void init()
MyObject = (MyObject)FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("obj");
}
1

1 Answers

2
votes

Your managed beans should have been @ViewScoped. Otherwise, you'd need to obtain it in (action)listener method such as <f:event>:

<f:event type="preRenderView" listener="#{bean.init}" />

wherein you obtain the session object in init() method.

public void init() {
    obj = (Obj) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("obj");
}

Or maybe lazily loaded in a getter if your sole purpose is to access it in EL:

public Obj getObj() {
    if (obj == null) {
        obj = (Obj) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("obj");
    }

    return obj;
}

But this makes no sense as the session scoped object is just available directly in EL by #{obj} without the need for an intermediating bean such as #{bean.obj}.

At least, the whole design makes no sense. That's why I suggested that they should actually have been @ViewScoped instead.

See also: