Access session scoped JSF managed bean in web filter

后端 未结 2 1929
太阳男子
太阳男子 2021-01-01 17:17

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

相关标签:
2条回答
  • 2021-01-01 17:57

    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:

    • Get JSF managed bean by name in any Servlet related class
    • Prevent accessing restricted page without login in Jsf2
    0 讨论(0)
  • 2021-01-01 17:57

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

    0 讨论(0)
提交回复
热议问题