如何在页面重新加载时保持JSF flash作用域参数



我使用flash作用域在@viewscoped控制器之间传递设置对象。但如果我在其中一个上重新加载一个页面,那么flash映射就是空的,设置对象也没有初始化。是否有可能保持flash范围在页面重新加载?

存储/检索设置的源代码:

FistPage.xhtml

...
<p:commandButton value="next"
    action="#{firstPageController.transferConfig}"  
    process="@this" />
...

FirstPageController.java

@ManagedBean(name = "firstPageController")
@ViewScoped
public class FirstPageController {
...
public String transferConfig() {
FacesContext.getCurrentInstance().getExternalContext().getFlash().put("searchConfig",   searchConfig);
return "/secondPage.xhtml?faces-redirect=true";
}
...
}

SecondPage.xhtml

...
<h:outputLabel value="value">
    <f:event type="preRenderComponent" listener="#{secondPageController.onPageLoad()}"/>
</h:outputLabel>
...

SecondPageController.java

@ManagedBean(name = "secondPageController")
@ViewScoped
public class SecondPageController {
    ...
    public void onPageLoad() 
    {
        flash = FacesContext.getCurrentInstance().getExternalContext().getFlash();
        searchConfig = ((SearchFilterConfig) flash.get("searchConfig"));
        flash.putNow("searchConfig", searchConfig);
        flash.keep("searchConfig");
    }
    ...
}

我使用Mojarra 2.1.29

谢谢

我刚刚在我的游乐场项目中做了一些测试,并意识到实际上可以保持flash参数的状态,即使您再次GET页面,使用{flash.keep}。JSF文档是这样解释的:

实现必须确保即使在<navigation-case>包含<redirect />的情况下也能保持闪存的正常行为。实现必须确保即使在同一会话上相邻的GET请求的情况下也能保留flash的正确行为。这允许Faces应用程序充分利用Post/Redirect/Get设计模式。

这里有一个很好的基本测试用例:

page1.xhtml

<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://xmlns.jcp.org/jsf/html"
    xmlns:c="http://java.sun.com/jsp/jstl/core">
<h:head />
<h:body>
    <h:form>
        <h:button id="nextButton" value="Next (button)" outcome="page2.xhtml" />
        <c:set target="#{flash}" property="foo" value="bar" />
    </h:form>
</h:body>
</html>

page2.xhtml

<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:h="http://java.sun.com/jsf/html">
<head />
<body>foo = #{flash.keep.foo}
</body>
</html>

只要打开第一页,点击按钮,就会重定向到第二页。然后根据需要多次刷新第二页,您会发现参数一直存在。


最新更新