Skip to content
javahacks.dev
JavaServer Faces

JSF Navigation Rules and Implicit Navigation Explained

Learn how JSF navigation works: implicit outcomes, faces-redirect, h:link versus h:commandLink, keeping messages and explicit navigation rules.

6 min read
Summarize in AI
Flat illustration of a browser page built from server-side components, with the OpenJDK, HTML5, CSS and Thymeleaf logos.

Navigation in JavaServer Faces is the step after an action: which page comes next. This post covers Jakarta Faces 4 and PrimeFaces 14 and later. The request cycle that triggers it is in the JSF lifecycle, and the overview is in the JSF guide.

Implicit navigation

XML
<h:form>
    <h:commandButton value="Save" action="#{orderBean.save}" />
</h:form>
java
@Named
@RequestScoped
public class OrderBean {
    public String save() {
        service.save(order);
        return "confirmation";             // goes to confirmation.xhtml
    }
}

The returned string is an outcome. If no explicit rule matches, Faces appends .xhtml and looks for that view in the same directory as the current one. A path starting with / is relative to the web root: return "/admin/orders". Returning null or an empty string redisplays the current view.

An action can also be a literal: action="confirmation" navigates without a method call.

Forward versus redirect

By default the target view is rendered in the same response, a forward. The browser URL still shows the old page, and pressing refresh resends the form. For a post that changes data, redirect:

java
return "confirmation?faces-redirect=true";

The response is a 302 to the new page, a pattern known as post-redirect-get. The URL is right, bookmarks work, and a refresh just reloads the confirmation. The price is a new request, so request-scoped state is lost. Keep what is needed in a view or session scoped bean, or in the flash:

java
FacesContext ctx = FacesContext.getCurrentInstance();
ctx.getExternalContext().getFlash().setKeepMessages(true);
ctx.addMessage(null, new FacesMessage("Order saved"));
return "orders?faces-redirect=true";

setKeepMessages(true) carries the messages across the redirect, so h:messages on the next page shows them. The validation side of messages is in validation, converters and messages.

Parameters

java
return "order?faces-redirect=true&id=" + order.getId();
XML
<f:metadata>
    <f:viewParam name="id" value="#{orderView.id}" />
    <f:viewAction action="#{orderView.load}" />
</f:metadata>

The page declares the parameter it expects, and Faces converts it to the bean property. f:viewAction runs a method after the parameters are set, which is the place to load data or reject a missing id.

XML
<h:link outcome="order" value="Open">
    <f:param name="id" value="#{order.id}" />
</h:link>
<h:button outcome="orders" value="Back" />

h:link and h:button render an anchor or a button that navigates with a GET request. They need no form and are crawlable. h:commandLink posts a form and runs an action, which is right for operations and wrong for plain navigation.

Explicit rules

XML
<navigation-rule>
    <from-view-id>/checkout.xhtml</from-view-id>
    <navigation-case>
        <from-outcome>done</from-outcome>
        <to-view-id>/confirmation.xhtml</to-view-id>
        <redirect/>
    </navigation-case>
</navigation-rule>

This is the XML style from early Faces. It still works, and it is useful for central control of a flow, but implicit navigation covers almost every case in a modern application.

Common problems

Navigation that goes nowhere is often not a navigation problem. If the action method is never called, validation failed in an earlier phase, or the button is outside a form, see command buttons that do nothing. If the target view is missing the result is a ViewNotFoundException.

Redirect after a post, and keep the message

The sequence that breaks most JSF forms is the refresh. A user saves an order, the action returns "orders" as a forward, the browser shows the list at the URL of the form, and pressing F5 resubmits the post. Returning "orders?faces-redirect=true" sends a 302 and the browser issues a GET, so refresh is harmless. The cost is that the request scope ends with the redirect, and the success message you added is lost before the next page renders.

The flash scope carries it across one redirect.

src/main/java/dev/javahacks/web/OrderBean.javajava
@Named
@ViewScoped
public class OrderBean implements Serializable {

    @Inject OrderService orders;
    private Order order = new Order();

    public String save() {
        orders.save(order);
        FacesContext context = FacesContext.getCurrentInstance();
        context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Order saved", null));
        context.getExternalContext().getFlash().setKeepMessages(true);
        return "orders?faces-redirect=true";
    }
}

The target page shows the message with an ordinary <h:messages />. Without setKeepMessages(true) the redirect works and the message disappears, which looks like a bug in the message component and is not.

A page that edits one order needs the id from the URL, and a bookmarkable link should open it. A view parameter binds the query string to a bean property, and a view action runs after binding, which is where loading belongs.

src/main/webapp/order.xhtmlXML
<f:metadata>
    <f:viewParam name="id" value="#{orderBean.id}" required="true" />
    <f:viewAction action="#{orderBean.load}" />
</f:metadata>
java
public String load() {
    order = orders.find(id);
    if (order == null) {
        return "notFound?faces-redirect=true";
    }
    return null;                         // stay on this page
}

required="true" produces a validation error when id is missing, and a ViewAction that returns an outcome performs navigation before the page renders, so a missing order becomes a redirect instead of a half rendered form. Returning null means no navigation. Links use <h:link outcome="order" value="Edit"><f:param name="id" value="#{o.id}" /></h:link>, which renders a plain GET link that search engines and bookmarks can follow.

Decide the outcome with a condition

Explicit rules in faces-config.xml still have a use when the target depends on state rather than on a string the bean returns. A rule can carry an <if> that is an EL boolean expression, so the page flow is visible in one file.

XML
<navigation-rule>
    <from-view-id>/checkout.xhtml</from-view-id>
    <navigation-case>
        <from-action>#{checkoutBean.pay}</from-action>
        <from-outcome>done</from-outcome>
        <if>#{cart.total gt 0}</if>
        <to-view-id>/receipt.xhtml</to-view-id>
        <redirect />
    </navigation-case>
    <navigation-case>
        <from-outcome>done</from-outcome>
        <to-view-id>/cart.xhtml</to-view-id>
        <redirect />
    </navigation-case>
</navigation-rule>

Cases are evaluated in order and the first match wins, so the unconditional fallback goes last. Use this sparingly. Rules scattered across large XML files are the maintenance cost that implicit navigation was introduced to remove.

Ask the navigation handler where an outcome leads

When a click goes nowhere, the quickest check is to ask JSF what it resolves for the outcome. The handler can be queried from code, for example in a debugging bean or a test.

java
ConfigurableNavigationHandler handler =
        (ConfigurableNavigationHandler) context.getApplication().getNavigationHandler();
NavigationCase target = handler.getNavigationCase(context, "#{orderBean.save}", "orders");
System.out.println(target == null ? "no case" : target.getToViewId(context));

A result of null means that neither an explicit rule nor an implicit page named orders.xhtml exists relative to the current view. The usual causes are a typo in the outcome, a page in a different folder (implicit navigation resolves relative to the current view), and an action method that is never invoked because validation failed earlier in the lifecycle. The last one is common enough to have its own post, command buttons that do nothing.

Which navigation style fits which page

Implicit navigation fits most pages, and the rest of the choice follows from what the user does next. A form that changes data should end in a redirect, so that a refresh repeats a harmless GET. A page that only displays something can be reached by a plain link, a <h:link> or <h:button>, because there is nothing to resubmit and the URL stays bookmarkable. An action that fails validation should stay on the same page, which is the default when the action returns null, so the user sees the error beside the field they have to correct.

Use explicit rules in faces-config.xml only when the same outcome string must lead to different pages depending on which page it came from, or when a conditional belongs in configuration. Teams that move to implicit navigation and then add conditions back into an XML file usually find the logic easier to follow when it is in the action method, where it can be unit tested in isolation from a servlet container.

Where this does not apply

Single-page style updates use AJAX with partial rendering, see f:ajax. Flows with several pages and shared state can use Faces Flows or CDI conversation scope. The reference is the Jakarta Faces specification, and the PrimeFaces documentation covers components.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.