了解JSF2中的Flash作用域

了解JSF2中的Flash作用域,jsf,jsf-2,flash-scope,Jsf,Jsf 2,Flash Scope,据我所知,放置在faces请求生命周期中Flash范围内的对象将可用于下一个faces请求生命周期,然后清除 假设我有两页: page01.xhtml: <h:form> <h:commandButton action="#{page01Bean.action}" /> </h:form> <h:outputText value="#{flash.fooKey}"/> page02.xhtml: <h:form>

据我所知,放置在faces请求生命周期中Flash范围内的对象将可用于下一个faces请求生命周期,然后清除

假设我有两页:

page01.xhtml

<h:form>
    <h:commandButton  action="#{page01Bean.action}" />
</h:form>
<h:outputText value="#{flash.fooKey}"/> 
page02.xhtml

<h:form>
    <h:commandButton  action="#{page01Bean.action}" />
</h:form>
<h:outputText value="#{flash.fooKey}"/> 

因此,当点击
page01.xhtml
中的按钮时,一个faces请求生命周期(比如生命周期a)开始,并在名为
fooKey

然后我打开另一个浏览器选项卡并浏览
page02.xhtml
。另一个faces请求生命周期(比如生命周期B)开始呈现此页面。我希望lifecycle B可以访问其上一个生命周期的flash范围(即生命周期A),并在
page02.xhtml
中显示
fooValue
。但是,它什么也不显示


请纠正我对exmaple中flash示波器的误解。非常感谢

简言之,存储在闪存作用域中的变量将在重定向后继续存在,并在重定向后被丢弃。这在实现Post重定向Get模式时非常有用

如果您试图通过重定向导航到另一个页面,并访问加载时的属性,它们将在那里。完成该请求后,闪存中的值将被丢弃。例如:

您在page1.xhtml中,有一个commandLink,它使用类似这样的方法重定向到新页面(注意:我将使用隐式导航)

呈现pageB.xhtml时,可以通过EL表达式访问这些值,例如


这将显示“Hello World!”字符串,我们在navigateToPageB中保存了该字符串


至于你的问题,在你的浏览器中打开一个新标签,你访问的上下文与你在上一个标签上访问的上下文不同,因此你的变量在那里不可用。

上一个答案是正确的,但为了完整性,我想说的是,在Mojarra实现中,有一个关于所有这些东西的例子,但最终他们实现了让它在Mojarra 2.1.27和2.2.5版本中正常工作

正如@Gamb所说,flash作用域的目的是使参数保持活动状态,并在重定向过程中对其进行内部映射。如果需要,我们还可以使参数保持更长的活动时间。除了上述方法,
FacesContext#getCurrentInstance#getExternalContext#getFlash#put
,还可以通过EL表达式设置参数,使用。我已经实现了以下一个基本测试,它使用两个视图显示了更广泛的选项:

Bean1

@ManagedBean
@ViewScoped
public class Bean1 implements Serializable {

    /**
     * Just takes the given param, sets it into flash context and redirects to
     * page2
     * 
     * @param inputValue
     * @return
     */
    public String goPage2(String inputValue) {
        FacesContext.getCurrentInstance().getExternalContext().getFlash()
                .put("param", inputValue);
        return "page2?faces-redirect=true";
    }

}
page1.xhtml


参数1:#{flash['param']}

Param2:#{flash['Param2']}

Bean2

@ManagedBean
@ViewScoped
public class Bean2 implements Serializable {

    public String getParam() {
        /**
         * Takes the parameter from the flash context
         */
        return (String) FacesContext.getCurrentInstance().getExternalContext()
                .getFlash().get("param");
    }

}
page2.xhtml


Param1:#{bean2.param}

Param1:#{flash.param}

参数1:#{flash['param']}

Param2:#{flash['Param2']}

#{flash.keep.param}
另请参见:

@ManagedBean
@RequestScoped
public class Page01Bean {

        public void action(){
            FacesContext.getCurrentInstance().getExternalContext().getFlash().put("fooKey", "fooValue");
        }

}

+1提到错误的实现,我感到非常困惑。设置它。EL没有为我做这件事,但我可以建议将它放在托管bean中:
FacesContext.getCurrentInstance().getExternalContext().getFlash().keep(“oValue”);this.oValue=(ValueClass)FacesContext.getCurrentInstance().getExternalContext().getFlash().get(“oValue”)
它适用于
GET
再次刷新页面,但在ajax请求+
GET
后,它会以某种方式中断。