• Post Reply Bookmark Topic Watch Topic
  • New Topic

Regarding sessions in servlets  RSS feed

 
yekkala krishna
Ranch Hand
Posts: 105
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

In my web application i need to retrieve different users accessing our application.so i am retrieving users information and displaying through servlets.But first request is coming as null.I didn't understand why first request is coming as null.Could anybody suggest what i need to do to overcome this problem?

regards,
rama
 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 66207
151
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I highly doubt that the request reference is null. Please elaborate more clearly what the issue is.
 
yekkala krishna
Ranch Hand
Posts: 105
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Bear,

Good to see your reply.Following is my code in the servlet:

HttpSession session=req.getSession();
HashMap sessionMap =(HashMap)session.getAttribute("ACTIVE_SESSION_LIST");
String userId =(String) session.getAttribute("GSAM_USER_ID");

System.out.println("username is ::"+userId);

Here i am able to retrieve GSAM_USER_ID as what ever i have given while login.But first request is displaying as null.
May i know why its displaying as null for first request.

Note:session object is creating properly.

regards,
rama
 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 66207
151
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yekkala krishna wrote:May i know why its displaying as null for first request.

Has the scoped variable been set prior to the first request? if not, null is expected.
 
Soniya Ahuja
Ranch Hand
Posts: 83
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

request.getSession() returns a new session if one does not exist. Once a new session is created for all subsequent requests, it will return the session as requested.

Now, when the session is created the first time, it does not have any attributes set on it. Hence, if your getAttribute call occurs immediately after creation of a new session, then it will return null as there are no attributes set on the new session.
Try this after request.getSession and before session.getAttribute

Please replace attributename and attributevalue with appropriate values.

Thus, you will see that the first time your session is created, the values that you set in the above if scope will be displayed.
Moral: Attributes need to be set before you can get them - else you will get a null.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!