HTML and CSS Reference
In-Depth Information
Listing 4-18. AuthorizationListener Phase Listener
package com.jsfprohtml5.firstapplication.model;
import javax.faces.application.NavigationHandler;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.servlet.http.HttpSession;
public class AuthorizationListener implements PhaseListener {
public void afterPhase(PhaseEvent event) {
FacesContext context = event.getFacesContext();
String currentPage = context.getViewRoot().getViewId();
boolean isLoginPage = currentPage.endsWith("index.xhtml");
HttpSession session = (HttpSession) context.getExternalContext().getSession(true);
Object isAuthenticated = session.getAttribute("isAuthenticated");
if (!isLoginPage && isAuthenticated == null) {
NavigationHandler navigationHandler = context.getApplication().getNavigationHandler();
navigationHandler.handleNavigation(context, null, "index");
public void beforePhase(PhaseEvent event) {
//Nothing ...
public PhaseId getPhaseId() {
return PhaseId.RESTORE_VIEW;
In order to implement page authorization, we need to create a phase listener on the JSF life cycle after the
RESTORE_VIEW phase is completed. In the afterPhase() API, the current page is retrieved using
context.getViewRoot().getViewId() . When the page is not the login page ( index.xhtml ) and the user is not
authenticated, then the user is forwarded to the login page using NavigationHandler . In order to install the phase
listener on the JSF life cycle, you need to define it in the faces configuration file, as shown in Listing 4-19.
Search WWH ::

Custom Search