Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I navigate to another page in managed bean?

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?

like image 709
yrazlik Avatar asked Jul 13 '13 16:07

yrazlik


People also ask

How do I navigate from one page to another in JSF?

JSF by default performs a server page forward while navigating to another page and the URL of the application does not change. To enable the page redirection, append faces-redirect=true at the end of the view name. Here, when Page1 button under Forward is clicked, you will get the following result.

Which return type of a method in a managed bean is used for page navigation?

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

What scopes are available for a managed bean?

You can specify one of the following scopes for a bean class: Application (@ApplicationScoped): Application scope persists across all users' interactions with a web application. Session (@SessionScoped): Session scope persists across multiple HTTP requests in a web application.


1 Answers

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:

  • Difference between h:button and h:commandButton
  • What is the difference between redirect and navigation/forward and when to use what?
  • How to navigate in JSF? How to make URL reflect current page (and not previous one)
  • ExternalContext#dispatch() doesn't work
  • JSF implicit vs. explicit navigation
like image 140
BalusC Avatar answered Oct 13 '22 23:10

BalusC