CommandButton使用FlashScope参数打开新选项卡

kar*_*kpl 4 jsf jsf-2

用户单击时如何打开新选项卡p:commandButton?我还想使用FlashScope将一些参数传递到新页面。这是代码:

<h:form>
  <p:commandButton value="open new tab" action="#{myBean.newTab}"/>
</h:form>

public String newTab() {
  Faces.setFlashAttribute("foo", bar);
  return "otherView";
}
Run Code Online (Sandbox Code Playgroud)

在otherView页面上,我用于f:event type="preRenderView"读取Flash参数。两个注意事项:

  1. 我需要使用FlashScope,而不是URL参数。
  2. 如果可能,我不想更改newTab()preRenderView()方法。

感谢帮助

Bal*_*usC 6

使用target="_blank"表单上告诉浏览器表单的同步响应应该在一个新的(空白)标签/窗口呈现。您只需要关闭的ajax行为<p:commandButton>即可使其成为同步请求。

<h:form target="_blank">
  <p:commandButton value="open new tab" action="#{myBean.newTab}" ajax="false" />
</h:form>
Run Code Online (Sandbox Code Playgroud)

支持bean不需要任何更改,它可以按照您的意图工作。我只建议在action方法中使用POST-Redirect-GET模式。

return "otherView?faces-redirect=true";
Run Code Online (Sandbox Code Playgroud)

否则,新选项卡将显示原始页面的URL,而F5将重新调用POST。同样,这种方式也确实使用了Flash作用域,因为它是专为它而设计的(如果您不重定向,仅存储在请求作用域中就足够了)。


更新:根据注释,初始选项卡/窗口中的视图作用域bean会被这种方式杀死。通过返回String导航案例结果。没错,如果您想保持视图范围的Bean处于活动状态,请通过Faces#redirect()调用替换导航用例(假设您确实使用了OmniFacesFaces#setFlashAttribute())。您只需预先设置Flash#setRedirect()true指示Flash作用域将发生重定向。

public void newTab() throws IOException {
    Faces.setFlashAttribute("foo", bar); 
    Faces.getFlash().setRedirect(true);
    Faces.redirect("otherView.xhtml");
}
Run Code Online (Sandbox Code Playgroud)