开发者

How to pass parameter from a RequestScoped to a ViewScoped bean

开发者 https://www.devze.com 2023-03-23 09:48 出处:网络
I have a simple form where you can input a String. When submitting the form, the user is redirected to another page that echos the user input. The first page is using a RequestScoped bean whereas the

I have a simple form where you can input a String. When submitting the form, the user is redirected to another page that echos the user input. The first page is using a RequestScoped bean whereas the second page is using a ViewScoped bean.

First Page:

    <h:form>
        Type a String: <h:inputText value="#{requestScopedBean.property}"></h:inputText>
        <h:commandButton value="To View" action="#{requestScopedBean.toViewScopedBean}">
            <f:setPropertyActionListener target="#{viewScopedBean.property}" value="#{requestScopedBean.property}" />
            <f:ajax execute="@form" />
        </h:commandBut开发者_C百科ton>
    </h:form>

Second Page:

    This is the property passed by the requestScoped bean: <h:outputText value="#{viewScopedBean.property}"></h:outputText><br/>
    This is the property created in the PostConstruct: <h:outputText value="#{viewScopedBean.otherProperty}"></h:outputText>

I understand why it does not work. When the form is submitted, the viewScopedBean.property is set to the correct value but then we switch to another view, so a new ViewScopedBean is created. That's why the value from the request is lost.

How do you pass the parameter from page one to page two without changing the scope of the bean?


Alternatively you could put the string on the request map when triggering the requestScopedBean action

public String toViewScopedBean(String string){
    Map<String,Object> requestMap = FacesContext.getCurrentInstance().getExternalContext().getRequestMap();
    requestMap.put("StringKey", string);
    return "toViewScopedBean";
}

and then retrieve the value from the valueScopedBean

public String getProperty(){
    Map<String, Object> requestMap = FacesContext.getCurrentInstance().getExternalContext().getRequestMap();
    return (String) requestMap.get("StringKey");
}
0

精彩评论

暂无评论...
验证码 换一张
取 消