JSF 2: page redirect after ajax call

2020-04-21 04:25发布

问题:

I'm stuck in a navigation case problem similar to this one. In a few words, I'm trying to redirect navigation from one page to another, using an ajax rendered h:commandLink. Here's the backing bean

@ManagedBean
public class StartBean {

    public void search(){
        FacesContext
            .getCurrentInstance()
            .getExternalContext()
            .getFlash()
            .put("result", "hooray!")
        ;
    }

    public String showResult(){
        return "result?faces-redirect=true";
    }
}

and the starting page

<h:body>
    <h:form prependId="false">
        <h:commandButton value="Click" action="#{startBean.search}">
            <f:ajax execute="@this" render="@form"/>
        </h:commandButton>

        <br/>

        <h:commandLink 
            action="#{startBean.showResult()}" 
            rendered="#{flash.result != null}" 
            value="#{flash.result}"
        />

    </h:form>
</h:body>

whereas result page is just showing a message. Both pages are on web module context root. It happens that the h:commandLink is correctly displayed after ajax submit, but clicking on it causes a page refresh. It doesn't redirect towards the result page, as expected. After it, if page is reloaded (F5), result page is shown. It seems to be a rendering cycle matter.

Any suggestion?

Thanks in advance.

回答1:

The rendered attribute of all input and command components is re-evaluated when the form is submitted. So if it evaluates false, then JSF simply won't invoke the action. The Flash scope is terminated when the request/response of the search() method is finished. It isn't there in the Flash scope anymore when you send the request of the showResult(). I suggest to put the bean in the view scope and bind the rendered attribute to its property instead.

@ManagedBean
@ViewScoped
public class StartBean {

    private String result;

    public void search(){
        result = "hooray";
    }

    public String showResult(){
        return "result?faces-redirect=true";
    }

    public String getResult() {
        return result;
    }

}

with

<h:commandLink 
    action="#{startBean.showResult}" 
    rendered="#{startBean.result != null}" 
    value="#{startBean.result}"
/>

See also:

  • commandButton/commandLink/ajax action/listener method not invoked or input value not updated