The following code shows how to check user role in JSF application.
The following code is from demo.xhtml.
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" > <f:event listener="#{user.isAdmin}" type="preRenderView" /> <h:body> <h1>JSF 2 protected page example</h1> </h:body> </html>
The following code is from UserBean.java.
package com.java2s.common; import javax.faces.application.ConfigurableNavigationHandler; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import javax.faces.context.FacesContext; import javax.faces.event.ComponentSystemEvent; @ManagedBean(name="user") @SessionScoped public class UserBean{ public void isAdmin(ComponentSystemEvent event){ FacesContext fc = FacesContext.getCurrentInstance(); if (!"admin".equals(fc.getExternalContext().getSessionMap().get("role"))){ ConfigurableNavigationHandler nav = (ConfigurableNavigationHandler) fc.getApplication().getNavigationHandler(); nav.performNavigation("access-denied"); } } }
The following code is from access-denied.xhtml.
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" > <h:body> <h1>Access Denied!</h1> </h:body> </html>
Copy the generated WAR file from the target folder to Tomcat deployment folder and run Tomcat-Install-folder/bin/startup.bat.
After Tomcat finish starting, type the following URL in the browser address bar.
http://localhost:8080/simple-webapp/demo.xhtml