Sunday, May 06, 2012

JSF 2 Tip of the Day: JSF Page Redirection in PhaseListener

I needed to redirect a user to a login page the other day, and solved it using a PhaseListener. Subsequently, I had another need to do a page redirection based on a value in the HttpSession. I thought I would share the general idea of how to do it with you.

The PhaseListener allows us to take action at various integration points in the JSF lifecycle. The most likely place you will want to handle an internal redirection, is before the view is restored. We use the JSF NavigationHandler to do the work for us.

PageRedirectionPhaseListener.java

2 comments :

Thang Pham said...

Hi John,
You want to redirect base on the value of HttpSession, and also your outcome view is static, I am assume that you want to redirect to login page after session expired. If that is the case, I feel like Filter should be a better use here (as Filter is great for block, redirect or modify the request). In Filter, you can obtain the session by:

request.getSession(false)

and if the HttpSession is null, then you can

response.sendRedirect("login.xhtml");

John Yeary said...

No I don't want to redirect after a session is expired. This is just a general purpose example of how to do it with a PhaseListener. Please don't read too much into it. The example is supposed to give you ideas. ;-)

The PhaseListener allows you to get the FacesContext and make decisions should you choose to do so.

Popular Posts