This post demonstrates how to retrieve a attribute from an HTTP Session
object in JSF 2
.
Requirements
Stuff used in this post.
- JSF 2.2
- javax.faces-2.2.8.jar
- JDK 8
Using FacesContext
[wp_ad_camp_1]
To access the HTTP Session
object, we need to use the FacesContext
to get an external context
. JSF
has its own context apart from the Servlet/JSP
context which in this case is our “external context”.
The following codes look for an attribute named "loggedIn"
in the HttpSession
object. If the attribute exists, we set sessionData
to that value. Otherwise, we set sessionData
to "false"
.
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 27 | package com.turreta.jsf.bean; ... @ManagedBean public class MyBean { private String sessionData; ... public void extractSessionData() { FacesContext facesContext = FacesContext.getCurrentInstance(); HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(false); Object loggedIn = session.getAttribute("loggedIn"); if(loggedIn == null) { sessionData = "false"; } else { sessionData = loggedIn.toString(); } } } |
This outputs:
[wp_ad_camp_2]
Testing
For testing purposes, we use another URL
to set the attribute "loggedIn"
in the HttpSession
object to "true"
.
If we click the same button in the previous page, the value is now "true"
.
[wp_ad_camp_3]
Download the codes
https://github.com/Turreta/JSF-Get-HTTP-Session-Attribute