簡體   English   中英

HttpSession - 如何獲取session.setAttribute?

[英]HttpSession - how to get the 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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM