简体   繁体   English

我不能使用@ManagedProperty访问会话范围变量吗?

[英]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. 基本上有三种方法可以实现所需的行为。

  1. 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"); // ... } } 
  2. Replace @SessionScoped by @RequestScoped . @SessionScoped替换为@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. 通过直接将其设置为bean属性来替换externalContext.getSessionMap().put("some", some)

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

See also: 也可以看看:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM