This post demonstrates how to check if user is logged in before a restricted page is displayed to the user.
[wp_ad_camp_1]
Requirements
Stuff used in this post.
- JSF 2.2
- javax.faces-2.2.8.jar
- JDK 8
Using Event preRenderView
preRenderView
is a system event that can be used to perform pre-processing before the a JSF
page is displayed. For example, the following codes use preRenderView
and invokes a managed bean method to perform a simple validation check.
[wp_ad_camp_2]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://xmlns.jcp.org/jsf/html" xmlns:a="http://xmlns.jcp.org/jsf/facelets" xmlns:f="http://xmlns.jcp.org/jsf/core"> <f:metadata> <f:event listener="#{myBean.isLoggedIn()}" type="preRenderView"></f:event> </f:metadata> <h:head> <title>Demo</title> </h:head> <h:body> This is your dashboard! Welcome! </h:body> </html> |
myBean.isLoggedIn
method has these codes:
[wp_ad_camp_3]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | package com.turreta.jsf.bean; import javax.faces.application.ConfigurableNavigationHandler; import javax.faces.bean.ManagedBean; import javax.faces.context.FacesContext; import javax.servlet.http.HttpSession; @ManagedBean public class MyBean { public void isLoggedIn() { FacesContext facesContext = FacesContext.getCurrentInstance(); HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(true); Object loggedIn = session.getAttribute("loggedIn"); if(loggedIn == null) { ConfigurableNavigationHandler nav = (ConfigurableNavigationHandler) facesContext.getApplication().getNavigationHandler(); nav.performNavigation("no-access"); } else { // Display dashboard.xhtml } } } |
ConfigurableNavigationHandler
is used to “forward” the user to another page.
[wp_ad_camp_4]
Download the codes
https://github.com/Turreta/JSF-Check-If-User-is-Logged-In-with-preRenderView