-->

How can I retrieve an object on @WindowScoped?

2020-04-21 07:47发布

问题:

In this post Dynamic ui:include I asked how I could store an object in some state that could permit me to load a new windows, or tab, of the same browser and it was not stored also in the new windows. Adrian Mitev told me to use @WindowScoped, an option of MyFaces extension called CODI and i tried to implement it.

Now I should say that I'm blind and when I tried to open Apache Wiki my browser crashes on many pages so I can't read the guides.

However I add the source code on my project and the compiler didn't give any errors. The problem is that now thepage when I try to retrive the bean that I stored by @WindowScoped doesn't work properly!

I use this code in my bean:

@ManagedBean (name="logicBean" )
@WindowScoped

In include.xhtml I retrieve the parameter with this code:

<ui:include src="#{logicBean.pageIncluded}"/> 

And in my other beans I retrieve the LogicBean with this code (and I'm sure that the problem is on this code)

LogicBean l = (LogicBean) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("logicBean");

How can I retrive the "correct" LogicBean object?

回答1:

You're trying to get the LoginBean from the session map. This works only for session scoped beans with the standard JSF @SessionScoped annotation.

The canonical way to access other beans is using @ManagedProperty on the retrieving bean.

E.g.

@ManagedBean
@RequestScoped
public class OtherBean {

    @ManagedProperty("#{logicBean}")
    private LogicBean logicBean;

    // Getter+Setter.
}

If you really need to access it inside the method block by evaluating the EL programmatically, you should be using Application#evaluateExpressionGet() instead:

FacesContext context = FacesContext.getCurrentInstance();
LogicBean logicBean = context.getApplication().evaluateExpressionGet(context, "#{logicBean}", LogicBean.class);
// ...