【问题标题】:ManagedBean and PropertyChangeListenerManagedBean 和 PropertyChangeListener
【发布时间】:2013-03-24 09:52:33
【问题描述】:

我有两个ManagedBeans@SessionScoped@ViewScoped):

@ManagedBean(name="sessionController")
@SessionScoped
public class SessionController implements Serializable{    
    private PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this);

    public void addPropertyChangeListener(PropertyChangeListener listener) {
        propertyChangeSupport.addPropertyChangeListener(listener);
    }

    ...
}

@ManagedBean(name="viewController")
@ViewScoped
public class ViewController implements Serializable, PropertyChangeListener{  
    @ManagedProperty(value="#{sessionController}")
    private SessionController sessionController ;  
    ...

    @PostConstruct
    public void init() {
        sessionController.addPropertyChangeListener(this);
    }


    @Override
        public void propertyChange(PropertyChangeEvent evt) {
            ...
        }

    }

我可以使用ViewController 中的PropertyChangeListener 来了解SessionController 的变化吗?会不会有什么问题?

【问题讨论】:

    标签: jsf-2 managed-bean propertychangelistener


    【解决方案1】:

    不,你不能。要将PropertyChangeSupport 添加到@SessionScoped bean,您需要调用

       propertyChangeSupport.addPropertyChangeListener("instanceofViewScopedBean")     
    

    在一个方便的地方(最好是@PostConstructor)。请注意,您需要将目标 bean 的实际实例(实现 PropertyChangeListener)传递给 addPropertyChangeListener。据我所知,您无法从会话 bean 中获取此信息,尤其是在 bean 初始化时。为什么?好吧,它是 viewscoped,它只在页面被查看时才存在。

    与此限制相关的是 JSF 策略,即托管 Bean 只能注入到更窄范围的其他 bean 中(使用您的情况,只有会话 bean 可以注入到 viewscoped bean 中)。您要做的几乎完全相反,将视图范围的 bean 绑定到会话范围的变量。

    我认为您正在尝试实现一种低成本的服务器端推送机制。好吧,除了好的轮询或彗星推动之外,我不知道还有其他方法可以完成这项工作。

    【讨论】:

    • 谢谢。现在我明白我的错误了。当然不能这样链接。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-20
    • 1970-01-01
    • 2011-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-04
    相关资源
    最近更新 更多