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
HttpSessionListenerinterface is used to monitor when sessions are created and destroyed on the application server. TheHttpSessionEvent.getSession()returns you a session that is newly created or destroyed (depending if it’s called bysessionCreated/sessionDestroyedrespectively).If you want an existing session, you will have to get the session from the request.