JSF.在每个页面加载时调用backing bean方法

Dfr*_*Dfr 6 jsf java-ee jsf-2

这是我的情况.

我有带数据表的页面和几个由bean支持的按钮.应该使用一些默认属性初始化Bean.可以根据操作更改属性.我从RequestScoped bean和@PostConstruct注释方法开始.但似乎datatable仅适用于View(Session)作用域.现在我的设置看起来像这样:

@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");
    }

    ...
Run Code Online (Sandbox Code Playgroud)

和来自jsf页面的片段:

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

以下是调用顺序中出现的主要问题,我有以下输出:

onPageLoad called
addRow called
onPageLoad called <-- :(
Run Code Online (Sandbox Code Playgroud)

但我希望addRow成为最后一个被调用的动作,如下所示:

onPageLoad called
addRow called
Run Code Online (Sandbox Code Playgroud)

这里有简单的解决方案

La *_*lle 8

查看此链接:http: //www.mkyong.com/jsf2/jsf-2-prerenderviewevent-example/

你知道事件是在每个请求上调用的:ajax,验证失败....你可以检查它是否是这样的新请求:

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");
    }
Run Code Online (Sandbox Code Playgroud)

  • 笨拙的`getMethod &&!ajaxRequest`可以用`!fc.isPostback()`代替.但毕竟,这绝不仅仅是一个`@ PostConstruct`,如果OP实际上所做的就是用`@ViewScoped`取代`@RequestScoped`(除非他**用'<f替换`@ManagedProperty` :viewParam>`,但这没有明确提到,因此我也对这个问题发表评论). (4认同)