10

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?

BalusC
  • 992,635
  • 352
  • 3,478
  • 3,452
yrazlik
  • 9,023
  • 26
  • 84
  • 145

1 Answers1

12

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:

Community
  • 1
  • 1
BalusC
  • 992,635
  • 352
  • 3,478
  • 3,452
  • thanks a lot, i think i did not know the difference between button and commandbutton. Just one more question, let us say for two pages i use the same managed bean, and at the page1 i have a textbox, i fill it and press button (not command button) setter and getter works and some variable is bound to value of that box. Then page1 is navigated to text2. You said that simple button does not perform a post request, so in page2 can i have the value of that variable which was bound to the value of the textbox in page1? Or do i have to pass it as a parameter to page2? – yrazlik Jul 13 '13 at 21:10
  • Depends on the concrete functional requirement. Why do you need to show results of POST request in a different view? Can't you just show the results conditionally in the same view by e.g. `rendered="#{not empty bean.results}"`? See also the 2nd "See also" link for recommendations. – BalusC Jul 13 '13 at 21:20