2012-06-13 63 views
4

驗證我的用戶後,我想在會話中將當前登錄用戶的引用。無法從Servlet過濾器中的FacesContext檢索會話

在這裏,我如何做到這一點的方法setCurrentUser

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

不幸的是,session參考總是空!

另外,我試圖與sessionMap

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

它悲慘地失敗了與此異常:

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

我在做什麼錯?

我的控制器的完整代碼

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

回答

11

FacesContext不可用作爲的Filter在之前FacesServlet之前調用

您應該從request參數中獲取會話。

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

一旦你在JSF上下文(例如內部JSF託管Bean或JSF視圖)非常相同的屬性名稱上,那麼這將是可利用getSessionMap()

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

或只是#{user}在EL:

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

這裏是我做過什麼:

public class SesionUtil implements Serializable { 

    private static final long serialVersionUID = 1L; 

    public void setSesionUsuario(String key, Object value) { 
     FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put(key, value); 
    } 

    public String getSesionUsuario(String key) { 
     return FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get(key).toString(); 
    } 
} 

然後,爲了初始化會話,我簡單地執行了:

@Inject // Inject dependency 
private SesionUtil sessionUtil; 

... 

sessionUtil.setSesionUsuario("nombreUsuario",nombre);