How can I navigate to another page in managed bean?

yrazlik picture yrazlik · Jul 13, 2013 · Viewed 18.2k times · Source

I am trying to forward a page in my managed bean with the commandbutton:

<h:commandButton action="#{bean.action}" value="Go to another page" />

The following line:

public void action() throws IOException {
    FacesContext.getCurrentInstance().getExternalContext().redirect("another.xhtml");
}

redirects the page, not forwards. I have seen a similar question to this and tried the given solution:

public void action() throws IOException {
    FacesContext.getCurrentInstance().getExternalContext().dispatch("another.xhtml");
}

But I get the following error:

Index: 0, Size: 0

So how can I forward to a page from a managed bean?

Answer

BalusC picture BalusC · Jul 13, 2013

Just return it as action method return value.

public String action() {
    return "another.xhtml";
}

If you're in turn not doing anything else than navigating, then you could also just put the string outcome directly in action attribute.

<h:commandButton action="another.xhtml" value="Go to another page" />

However, this is in turn a rather poor practice. You should not be performing POST requests for plain page-to-page navigation. Just use a simple button or link:

<h:button outcome="another.xhtml" value="Go to another page" />

See also: