HttpSession – 如何获取session.setAttribute?

我正在以这种方式创建HttpSession容器:

@SessionScoped @ManagedBean(name="userManager") public class UserManager extends Tools { /* [private variables] */ ... public String login() { /* [find user] */ ... FacesContext context = FacesContext.getCurrentInstance(); session = (HttpSession) context.getExternalContext().getSession(true); session.setAttribute("id", user.getID()); session.setAttribute("username", user.getName()); ... System.out.println("Session id: " + session.getId()); 

我有SessionListener,它应该给我关于创建的会话的信息:

 @WebListener public class SessionListener implements HttpSessionListener { @Override public void sessionCreated(HttpSessionEvent event) { HttpSession session = event.getSession(); System.out.println("Session id: " + session.getId()); System.out.println("New session: " + session.isNew()); ... } } 

如何获取username属性?

如果我使用System.out.println("User name: " + session.getAttribute("username"))尝试它,则抛出java.lang.NullPointerException ..

HttpSessionListener接口用于监视在应用程序服务器上创建和销毁会话的时间。 HttpSessionEvent.getSession()返回一个新创建或销毁的会话(取决于它是否分别由sessionCreated / sessionDestroyed调用)。

如果您想要现有会话,则必须从请求中获取会话。

 HttpSession session = request.getSession(true). String username = (String)session.getAttribute("username"); 

如果找到给定键,则session.getAttribute("key")返回java.lang.Object类型的值。 否则返回null。

 String userName=(String)session.getAttribute("username"); if(userName!=null) { System.out.println("User name: " + userName); }