Win a copy of Java Concurrency Live Lessons this week in the Threads forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Not get the session value  RSS feed

 
alona ariel
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I write a classe with a session

HttpSession session = request.getSession(true);
session.setAttribute("KEY",i2);

Now when I write another classe when I used the code
session.getAttribute("KEY");
it get the value of the session.

but when I used the code

HttpSession session = request.getSession(true);
String name = (String) session.getAttribute("KEY");
The parameter name did not get the value of the session.
why it happened?
how I can improve the code so that the parameter name will get the sossion value?
 
Tim Frith
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you do this:
HttpSession session = request.getSession(true);

you are creating a new session.

Do this instead:
HttpSession session = request.getSession();
 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13078
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Any programmer working with servlets should study the javax.servlet.http.HttpServletRequest API carefully.

request.getSession( true ) creates a session if one does not already exist.

To detect whether a session already exist,

request.getSession( false ) returns null if none exists.

Probably in your test case, the session had already expired, you got a new session object.

Bill
 
alona ariel
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I try to learn the session better, but my problem is why the KEY value is saved in the jsp, but isn't saved in the servlet?
How can I read the session session.setAttribute("KEY",i2); in a new servlet?
 
Ulf Dittmer
Rancher
Posts: 42970
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Didn't Tim and Bill both tell you why? They even both showed how the code should read correctly.
 
Hebert Coelho
Ranch Hand
Posts: 754
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
alona ariel wrote:I try to learn the session better, but my problem is why the KEY value is saved in the jsp, but isn't saved in the servlet?
How can I read the session session.setAttribute("KEY",i2); in a new servlet?


Come on. Just read what Tim and Bill wrote for you. The answer is there...
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!