jsfsessionservlet-filtersfacescontext

Failed to retrieve Session from FacesContext inside a Servlet Filter


After autheticating my user, I want to put a reference in the session to current logged in user.

Here how I do it in the setCurrentUser method :

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

Unfortunately, the session reference is always null !

Alternatively, I tried with the sessionMap

FacesContext facesContext = FacesContext.getCurrentInstance();
Map<String, Object> sessionMap = facesContext.getExternalContext().getSessionMap();
sessionMap.put("CURRENT_USER", currentUser);

It miserably failed with this exception :

java.lang.UnsupportedOperationException
    at java.util.AbstractMap.put(AbstractMap.java:186)
    (...)

What am I doing wrong ?

The full code of my controller

UserController.java

public class UserController implements Filter {
    private FilterConfig fc;
    private static final String CURRENT_USER = "CURRENT_USER";

    public void init(FilterConfig filterConfig) throws ServletException {
        fc = filterConfig;
        log(">> Filter initialized");
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // Authenticate user
        // ...

        // Save refernce in Session
        setCurrentUser(currentUser);

        //(...)
    }

    public static void setCurrentUser(User u) {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(true);
        session.setAttribute(CURRENT_USER, u);// session is always NULL
    }

    public static User getCurrentUser() {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(true);       
        return (User)session.getAttribute(CURRENT_USER);
    }

    //...   
}

JSF 2.0
JBoss 5.1.0.GA


Solution

  • The FacesContext is not available in a Filter as the Filter is invoked before the FacesServlet.

    You should be getting the session from the request argument instead.

    HttpSession session = ((HttpServletRequest) request).getSession();
    session.setAttribute("user", currentUser);
    // ...
    

    Once you're in JSF context (e.g. inside a JSF managed bean or a JSF view), then this will be available by getSessionMap() on the very same attribute name

    User user = (User) externalContext.getSessionMap().get("user");
    

    Or just by #{user} in EL:

    @ManagedProperty("#{user}")
    private User user;