Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this the correct way to integrate a ViewScoped and RequestScoped bean?

Tags:

jsf-2

I have a page that is backed by a ViewScoped Managed Bean. The page has a dialog on it (I'm using primefaces) that is backed by a RequestScoped ManagedBean. I chose to make the dialog's managed bean request scoped so that it would be cleared out any time the dialog was launched (basically the use case is that user opens the dialog, fills out some data, and then the data is ADDED to the page that is backed by the ViewScoped Managed Bean).

The way that I'm integrating the two beans is through a ManagedProperty on the dialog's RequestScoped bean. i.e. the ViewScoped bean is injected into the RequestScoped bean. On save of the dialog an actionListener method on the Dialog's RequestScoepd Bean updates the property on the ViewScoped bean that holds a reference to the RequestScoped ManagedBean with the current instance of the bean. Then the actionListener on the ViewScoped managed bean is invoked by the request scoped bean. The actionListneer in the ViewScoped managed bean is therefore able to work with the newly injected RequestScoped ManagedBean.

Is this a good way to do what I'm trying to do or is there a better way?

Sample code:

@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);
    }
}
like image 537
BestPractices Avatar asked Mar 22 '12 14:03

BestPractices


1 Answers

The cooperation makes perfectly sense. Only the DialogValue property and handleDialogSave() method are superfluous in PageBackingBean and might be confusing for the future maintainer. You could instead also just do this in DialogValue backing bean.

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

And maybe rename the DialogValue to DialogBacking or something, at least its name shouldn't suggest being just a model.

like image 83
BalusC Avatar answered Sep 18 '22 17:09

BalusC