0

I know I can put/get session scope variables like this.

FacesContext.getCurrentInstance().getExternalContext()
    .getSessionMap().put(SESSION_KEY_SOME, some);

Then can't I access the value like this?

@ManagedBean
@SessionScoped
public class SomeOtherBean {

    @ManagedProperty("#{sessionScope.some}")
    private Some some;
}

The value is null.

Jin Kwon
  • 20,295
  • 14
  • 115
  • 184

1 Answers1

1

@ManagedProperty runs during creation/instantiation of the @ManagedBean.

So, when the @ManagedBean is created before the #{sessionScope.some} is set for first time, then it will still remain null in the @ManagedBean. It will only work when @ManagedBean is created after the #{sessionScope.some} is set for the first time.

There are basically three ways to achieve the desired behavior.

  1. Replace private Some some by externalContext.getSessionMap().get("some").

    @ManagedBean
    @SessionScoped
    public class SomeOtherBean {
    
        public void someMethod() {
            Some some = (Some) FacesContext.getCurrentInstance()
                .getExternalContext().getSessionMap().get("some");
            // ...
        }
    
    }
    
  2. Replace @SessionScoped by @RequestScoped.

    @ManagedBean
    @RequestScoped
    public class SomeOtherBean {
    
        @ManagedProperty("#{sessionScope.some}")
        private Some some;
    
        // ...
    }
    
  3. Replace externalContext.getSessionMap().put("some", some) by directly setting it as bean property.

    @ManagedBean
    public class SomeBean {
    
        @ManagedProperty("#{someOtherBean}")
        private SomeOtherBean someOtherBean;
    
        public void someMethod() {
            // ...
            someOtherBean.setSome(some);
        }
    
        // ...
    }
    

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555