It would seem that the following are equivalent:
FacesContext.getCurrentInstance().getApplication().getNavigationHandler().handleNavigation("/index.xhtml?faces-redirect=true");
FacesContext.getCurrentInstance().getExternalContext().redirect("/testapp/faces/index.xhtml");
Are there any differences and when should each be used?
With the
NavigationHandler#handleNavigation()approach you’re dependent on the implemented navigation handlers. You or a 3rd party could easily overridde/supply this in the webapp. This can be advantageous if you want more fine grained control, but this can be disadvantagrous if you don’t want to have external controllable influences at all. Using certain URLs and/or parameters could potentially result in a different navigation behaviour.The
ExternalContext#redirect()delegates under the covers immediately toHttpServletResponse#sendRedirect(), without involving any navigation handler. So that may be an advantage when using the navigation handler is potentially disadvantageous. But the disadvantage is that it doesn’t handle implicit navigation nor takes definied navigation cases into account.All in all, it depends 🙂 If you just want a fullworthy and to-the-point redirect, use the
ExternalContext#redirect(). If you want to navigate by an outcome instead of an URL, useNavigationHandler#handleNavigation().See also: