在验证我的用户之后,我想在会话中将引用添加到当前登录用户。
我在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)
(...)
我做错了什么?
我的控制器的完整代码
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
答案 0 :(得分:11)
FacesContext
中的Filter
不可用Filter
,因为在<{em> FacesServlet
之前调用了request
。
您应该从HttpSession session = ((HttpServletRequest) request).getSession();
session.setAttribute("user", currentUser);
// ...
参数获取会话。
getSessionMap()
一旦进入JSF上下文(例如,在JSF托管bean或JSF视图中),User user = (User) externalContext.getSessionMap().get("user");
将在同一属性名称上提供此内容
#{user}
或者只是EL中的@ManagedProperty("#{user}")
private User user;
:
{{1}}
答案 1 :(得分:-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);