简体   繁体   中英

HttpSession - how to get the session.setAttribute?

I'm creating HttpSession container this way:

@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());

And I have SessionListener which should gives me info about session created:

@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());
    ...
  }
}

How can I get the username attribute?

If I'm trying it using System.out.println("User name: " + session.getAttribute("username")) it throws java.lang.NullPointerException ..

The HttpSessionListener interface is used to monitor when sessions are created and destroyed on the application server. The HttpSessionEvent.getSession() returns you a session that is newly created or destroyed (depending if it's called by sessionCreated / sessionDestroyed respectively).

If you want an existing session, you will have to get the session from the request.

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

The session.getAttribute("key") return a value of java.lang.Object type if given key is found. It returns null otherwise.

String userName=(String)session.getAttribute("username");

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM