Access session scoped JSF managed bean in web filter
Asked Answered
P

2

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.

Pentagrid answered 22/1, 2013 at 15:24 Comment(1)
Related: How can I get session scoped bean in filter from session? (jsf 2.1)Crepuscular
E
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:

Endbrain answered 22/1, 2013 at 15:49 Comment(2)
What can I tell you @Endbrain you should be awarded as the Master of JSF.Inoperable
@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(<userBean>) doesn't work with CDI. Thx.Gerdes
A
4

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

Arango answered 22/1, 2013 at 19:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.