这是集成ViewScoped和RequestScoped bean的正确方法吗?

时间:2012-03-22 14:38:39

标签: jsf-2

我有一个由ViewScoped Managed Bean支持的页面。该页面上有一个对话框(我正在使用primefaces),它由RequestScoped ManagedBean支持。我选择使对话框的托管bean请求作用域,以便在对话框启动时将其清除(基本上用例是用户打开对话框,填写一些数据,然后将数据添加到页面中由ViewScoped Managed Bean支持。

我正在集成两个bean的方式是通过对话框的RequestScoped bean上的ManagedProperty。即ViewScoped bean被注入RequestScoped bean。在保存对话框时,Dialog的RequestScoepd Bean上的actionListener方法更新ViewScoped bean上的属性,该属性包含对当前Bean实例的RequestScoped ManagedBean的引用。然后,请求范围bean调用ViewScoped托管bean上的actionListener。因此,ViewScoped托管bean中的actionListneer可以使用新注入的RequestScoped ManagedBean。

这是做我正在尝试做的好方法还是有更好的方法?

示例代码:

@ManagedBean
@ViewScoped
public class PageBackingBean
{
    List<DialogValue> dialogValues;

    DialogValue dialogValue;

    public void setDialogValue(DialogValue dialogValue)
    {
        this.dialogValue = dialogValue);
    }

    public DialogValue getDialogValue() { return dialogValue; }

    public void handleDialogSave(ActionEvent event)
    {
        dialogValues.add(getDialogValue());
    }
}

@ManagedBean
@RequestScoped
public class DialogValue
{
    @ManagedProperty(#{pageBackingBean})
    PageBackingBean pageBackingBean;

    String val1;
    String val2;

    // getters/setters ommitted for brevity...

    public void dialogSave(ActionEvent event)
    {
        pageBackingBean.setDialogValue(this);
        pageBackingBean.handleDialogSave(event);
    }
}

1 个答案:

答案 0 :(得分:2)

合作非常有意义。 DialogValue中只有handleDialogSave()属性和PageBackingBean方法是多余的,可能会让未来的维护者感到困惑。您也可以在DialogValue支持bean中执行此操作。

public void dialogSave(ActionEvent event)
{
    pageBackingBean.getDialogValues().add(dialogValue);
}

也许可以将DialogValue重命名为DialogBacking或其他内容,至少它的名称不应该仅仅是一个模型。

相关问题