HttpSession - how to get session.setAttribute?

I create an HttpSession container as follows:

@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 a SessionListener that should give me information about the created session:

 @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 try to use System.out.println("User name: " + session.getAttribute("username")) , it throws java.lang.NullPointerException ..

+7
source share
2 answers

The HttpSessionListener interface is used to monitor when sessions are created and destroyed on the application server. HttpSessionEvent.getSession() returns you a session that was recently created or destroyed (depending on whether it was sessionCreated / sessionDestroyed respectively).

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

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

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

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

All Articles