HttpSession - 如何获取session.setAttribute?

gaf*_*fcz 9 java jsf listener java-ee

我正在以这种方式创建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());
Run Code Online (Sandbox Code Playgroud)

我有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());
    ...
  }
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能获得该username属性?

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

Buh*_*ndi 13

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

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

HttpSession session = request.getSession(true).
String username = (String)session.getAttribute("username");
Run Code Online (Sandbox Code Playgroud)