使用 p:commandButton 导航时调用 f:viewAction 中的操作

Invoke action in f:viewAction while navigating using p:commandButton

home.xhtml

<p:button outcome="product" value="Login Simple Button"/>
<p:commandButton value="Login" action="#{homeController.validate}" update="logindialog"/>

product.xhtml

<f:metadata> <f:viewAction action="#{productController.readProductGroup}" /> </f:metadata>

简单 p:button 导航并成功调用 readProductGroup();但是 p:commandButton 即使 homeController.validate() 方法 returns 'product' 并成功导航到 product.xhtml.

使用 p:button,我无法灵活地调用服务器方法、使用更新属性等我需要的。

我需要的是,能够在 home.xhtml 页面按钮中使用更新、action/actionListener 等属性,同时导航到 product.xhtml,应该是能够在页面加载时调用 f:metadata 下的函​​数 productController.readProductGroup。

求推荐。

<f:viewAction> 旨在 运行 GET 请求,而不是 POST 请求。要对 POST 请求调用操作,您应该使用 <h:commandXxx>.

如果出于某种原因你真的想要 运行 <f:viewAction> 对 POST 请求,那么只需将其 onPostback 属性设置为 true

<f:viewAction ... onPostback="true" />

另一方面,也有可能您不太了解幂等性、导航和 GET 与 POST。按 POST 导航被认为是不好的做法。您可以通过将 ?faces-redirect=true 查询字符串附加到结果来发送重定向操作方法来应用 POST-redirect-GET 模式。

public void validate() {
    // ...

    return "product?faces-redirect=true";
}

另见 How to navigate in JSF? How to make URL reflect current page (and not previous one)


与具体问题无关,操作方法名称给我的印象是您也没有意识到正确使用 JSF 验证器。那样的话,仔细阅读JSF 2.0 validation in actionListener or action method.