本文介绍了Web过滤器中访问会话范围的JSF托管Bean的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为userSession的SessionScoped bean来跟踪用户(用户名,ifLogged等).我想过滤一些页面,因此我需要从我创建的webFilter中访问bean.我怎么做?我看起来甚至不可能导入该bean,使其具有潜在的可见性.

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.

推荐答案

在幕后,JSF将会话范围的托管bean作为 HttpSession ,其中受管bean名称为键.

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

因此,假设您拥有@ManagedBean @SessionScoped public class User {},则只需在doFilter()方法内部执行此操作即可

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.
}

或者,如果您实际上是在使用CDI而不是JSF来管理bean,那么直接在过滤器中直接使用@Inject.

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

  • Get JSF managed bean by name in any Servlet related class
  • Prevent accessing restricted page without login in Jsf2

这篇关于Web过滤器中访问会话范围的JSF托管Bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 16:38