[英]Can't I access session scope variable using @ManagedProperty?
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
. 该值为
null
。
@ManagedProperty
runs during creation/instantiation of the @ManagedBean
. @ManagedProperty
的创建/实例化过程中运行@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
. 因此,在第一次设置
#{sessionScope.some}
之前创建@ManagedBean
时,它在@ManagedBean
仍将为null
。 It will only work when @ManagedBean
is created after the #{sessionScope.some}
is set for the first time. 仅在首次设置
#{sessionScope.some}
之后创建@ManagedBean
时,它才起作用。
There are basically three ways to achieve the desired behavior. 基本上有三种方法可以实现所需的行为。
Replace private Some some
by externalContext.getSessionMap().get("some")
. 用
externalContext.getSessionMap().get("some")
替换private Some some
。
@ManagedBean @SessionScoped public class SomeOtherBean { public void someMethod() { Some some = (Some) FacesContext.getCurrentInstance() .getExternalContext().getSessionMap().get("some"); // ... } }
Replace @SessionScoped
by @RequestScoped
. 将
@SessionScoped
替换为@RequestScoped
。
@ManagedBean @RequestScoped public class SomeOtherBean { @ManagedProperty("#{sessionScope.some}") private Some some; // ... }
Replace externalContext.getSessionMap().put("some", some)
by directly setting it as bean property. 通过直接将其设置为bean属性来替换
externalContext.getSessionMap().put("some", some)
。
@ManagedBean public class SomeBean { @ManagedProperty("#{someOtherBean}") private SomeOtherBean someOtherBean; public void someMethod() { // ... someOtherBean.setSome(some); } // ... }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.