在对我的用户进行身份验证后,我想在会话中引用当前登录的用户。
这里我如何在setCurrentUser
方法中做到这一点:
FacesContext facesContext = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(true);
session.setAttribute("CURRENT_USER", currentUser);
不幸的是,session
引用总是 null !
或者,我尝试使用 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)
(...)
我究竟做错了什么 ?
我的控制器的完整代码
用户控制器.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