16

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?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Ryan
  • 7,499
  • 9
  • 52
  • 61

1 Answers1

16

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 to HttpServletResponse#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, use NavigationHandler#handleNavigation().

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • 1
    I guess another small difference is the NavigationHandler approach requires a viewId whereas the ExternalContext approach requires an actual URL. In both of the cases I assume the FacesContext.getCurrentInstance().responseComplete() is unnecessary. – Ryan Jun 08 '11 at 17:41
  • Yes, this is what I meant with "outcome". – BalusC Jun 08 '11 at 17:43
  • For others reading this post: another API level difference is the ExternalContext approach throws a checked exception (IOException) and the NavigationHandler approach doesn't. – Ryan Jun 09 '11 at 12:50
  • 1
    Which you don't necessarily need to handle. It's unrecoverable anyway (e.g. connection reset by peer). Just add `throws IOException` to the method wherein you call `ExternalContext#redirect()` and let JSF/webbrowser handle it by itself. – BalusC Jun 09 '11 at 12:56