title: Setting/getting session attribute in JSF
body: <p>I am trying to implement simple log in functionality in a JSF application. Following this <a href="https://stackoverflow.com/a/8480241/945945">answer</a>, I have implemented an AuthenticationFilter. I am trying to set an object in my managed bean as :</p>
  
  <pre><code>FacesContext facesContext = FacesContext.getCurrentInstance();
  HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(true);
  session.setAttribute("user", user);
  </code></pre>
  
  <p>doFilter method of AuthenticationFilter looks like this:</p>
  
  <pre><code>    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);
         }
     }
  </code></pre>
  
  <p>I always get <code>((HttpServletRequest) req).getSession().getAttribute("user") == null</code> (true). I have searched and applied many <strong>alternatives</strong> like (in my bean) :</p>
  
  <pre><code>facesContext.getExternalContext().getSessionMap().put("user", user);
  request.getSession().setAttribute("user", user);
  session.getServletContext().setAttribute("user", user); // DISASTER 
  </code></pre>
  
  <p>I don't have a clue how to manage this thing. Seemingly <a href="https://stackoverflow.com/questions/9815964/object-is-null-in-the-session-attribute-map-when-accessed-from-servlet-filter">duplicate question</a> did'nt help either. What am I doing wrong? How can I make it work? Is there a good and clean way to do it using JSF capabilities? </p>