【问题标题】:Setting/getting session attribute in JSF在 JSF 中设置/获取会话属性
【发布时间】:2012-06-18 06:39:23
【问题描述】:

我正在尝试在 JSF 应用程序中实现简单的登录功能。在这个answer 之后,我实现了一个AuthenticationFilter。我正在尝试在我的托管 bean 中设置一个对象:

FacesContext facesContext = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(true);
session.setAttribute("user", user);

AuthenticationFilter 的 doFilter 方法如下所示:

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {

       if (((HttpServletRequest) req).getSession().getAttribute("user") == null){   
            ((HttpServletResponse) resp).sendRedirect("../login.jsf");

       } else {
         chain.doFilter(req, resp);
       }
   }

我总是得到((HttpServletRequest) req).getSession().getAttribute("user") == null(真的)。我已经搜索并应用了许多 alternatives,例如(在我的 bean 中):

facesContext.getExternalContext().getSessionMap().put("user", user);
request.getSession().setAttribute("user", user);
session.getServletContext().setAttribute("user", user); // DISASTER 

我不知道如何管理这件事。似乎duplicate question 也没有帮助。我究竟做错了什么?我怎样才能让它工作?有没有一种使用 JSF 功能的好方法?

【问题讨论】:

  • JSESSIONID cookie 是否在浏览器的请求中正确维护?跟踪 HTTP 流量。

标签: session jsf authentication servlet-filters


【解决方案1】:

我建议您使用像上一个答案一样的安全库。错误的方法太多了...

但是,如果您一心想要自己动手,请不要在 Session 中设置它。声明一个 ManagedBean 并将其限定为会话级别。让 bean 的属性成为用户名。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-28
    • 1970-01-01
    • 2015-09-03
    • 1970-01-01
    • 2010-10-07
    相关资源
    最近更新 更多