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
..
You can access an HttpSession object in the service method of your servlet. Proceed as follows: Use the request. getSession() method of the HttpServletRequest object.
Method 6: setAttribute(String, object): The setAttribute method is used to store an object in session by allotting a unique string to the object. Later, By using the same string this object can be accessed from the session until the session is active.
The HttpSession interface is used to create a session between the client and server. The session is created between an HTTP Client and an HTTP Server by the servlet container using this interface. The Java Web Server keeps track of each user on the site by creating a session object of interface HttpSession.
When you use request. getSession(). setAttribute() , you store something for that particular user session. You can use this attribute whenever you want if the user session has not expired.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With