18

I have SessionScoped bean called userSession to keep track of the user ( username, ifLogged, etc). I want to filter some pages and therefore I need to access the bean from the webFilter I created. How do I do that? I looks like its even impossible to import the bean to be potenitally visible.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
user1997553
  • 233
  • 1
  • 2
  • 10
  • Related: [How can I get session scoped bean in filter from session? (jsf 2.1)](http://stackoverflow.com/q/12748648/1065197) – Luiggi Mendoza Jan 22 '13 at 15:27

2 Answers2

28

Under the covers, JSF stores session scoped managed beans as an attribute of the HttpSession with the managed bean name as key.

So, provided that you've a @ManagedBean @SessionScoped public class User {}, just this should do inside the doFilter() method:

HttpSession session = ((HttpServletRequest) request).getSession(false);
User user = (session != null) ? (User) session.getAttribute("user") : null;

if (user != null && user.isLoggedIn()) {
    // Logged in.
}

Or, if you're actually using CDI instead of JSF to manage beans, then just use @Inject directly in the filter.

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • 1
    What can I tell you @BalusC you should be awarded as the Master of JSF. – Jalal Sordo Jun 25 '16 at 04:43
  • @BalusC: And how can I check whether the CDI injected (session) bean has been instantiated or not without calling a method on that bean (which would create the bean if it doesn't exist yet)? `session.getAttribute()` doesn't work with CDI. Thx. – Toru Dec 03 '18 at 08:24
4

As an alternative you can use CDI-beans and inject your sessionbean normally.

Karl Kildén
  • 2,415
  • 22
  • 34