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.s开发者_Python百科etAttribute("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);
}
精彩评论