HttpSession - 如何获取session.setAttribute?

2024-04-19

我以这种方式创建 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..


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

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

HttpSession session = request.getSession(true).
String username = (String)session.getAttribute("username");
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

HttpSession - 如何获取session.setAttribute? 的相关文章

随机推荐