参见英文答案 >
Invoke JSF managed bean action on page load4个
这是我的情况.
这是我的情况.
我有带数据表的页面和几个由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"); } ...
和来自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>
onPageLoad called addRow called onPageLoad called <-- :(
但我希望addRow成为最后一个被调用的动作,如下所示:
onPageLoad called addRow called
这里有简单的解决方案
解决方法
检查此链接:
http://www.mkyong.com/jsf2/jsf-2-prerenderviewevent-example/
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"); }