Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSF. Call backing bean method on every page load [duplicate]

here is my situation in short.

I have page with datatable and few buttons backed by bean. Bean should be initialized with some default properties. That properties can be changed depending on action. I started with RequestScoped bean and @PostConstruct annotated method. but it seems that datatable works well only with View(Session)scoped. Now my setup look like this:

@ManagedBean
@ViewScoped
public class ProductsTableBean implements Serializable {

    private LazyDataModel<Products> productsData;
    @Inject
    private ProductsFacade model;


    public void onPageLoad() {
       // here some defaults are set
       // ...
       System.err.println("onPageLoad called");
    }

    public void addRow() {
       // andhere some defaults redefined
       // ...
       System.err.println("addRow called");
    }

    ...

and snippet from jsf page:

    <p:commandButton action="#{productsTableBean.addRow()}"
                     title="save"
                     update="@form" process="@form" >
    </p:commandButton>
    ...
    <f:metadata>
        <f:event type="preRenderView" listener="#{productsTableBean.onPageLoad}"/>
    </f:metadata>

And here is the main problem arise in calling order, i have following output:

onPageLoad called
addRow called
onPageLoad called <-- :(

But i want addRow to be the last action to be called, like this:

onPageLoad called
addRow called

Any simple solution here ?

like image 892
Dfr Avatar asked Aug 06 '12 10:08

Dfr


1 Answers

Check this link : http://www.mkyong.com/jsf2/jsf-2-prerenderviewevent-example/

You know that the event is call on every requests : ajax, validation fail .... You can check if it's new request like this:

public boolean isNewRequest() {
        final FacesContext fc = FacesContext.getCurrentInstance();
        final boolean getMethod = ((HttpServletRequest) fc.getExternalContext().getRequest()).getMethod().equals("GET");
        final boolean ajaxRequest = fc.getPartialViewContext().isAjaxRequest();
        final boolean validationFailed = fc.isValidationFailed();
        return getMethod && !ajaxRequest && !validationFailed;
    }

public void onPageLoad() {
       // here some defaults are set
       // ...
if (isNewRequest()) {...}
       System.err.println("onPageLoad called");
    }
like image 140
La Chamelle Avatar answered Oct 09 '22 07:10

La Chamelle