• Post Reply Bookmark Topic Watch Topic
  • New Topic

Session variable  RSS feed

 
sijin r s
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have found difficulty in using session variables in jsp. plz give examples with explanation.
 
Srilakshmi Vara
Ranch Hand
Posts: 169
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Srini,

Session is one of the default objects in JSP, You can use HttpSession as session in JSP, Set/get Attributes using setAttribute("variablename","variablevalue) and
getAttribute("variablename") this return objects you can cast it to the required type.

Srilakshmi
 
Srilakshmi Vara
Ranch Hand
Posts: 169
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry to mispell your name Sijin!!
 
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
"sijin r s",

Speaking of names... there aren't may rules that you need to worry about here on the Ranch, but one that we take very seriously regards the use of proper names. Please take a look at the JavaRanch Naming Policy and adjust your display name to match it.

In particular, your display name must be a first and a last name separated by a space character, and must not be obviously fictitious.

Thanks!
bear
Forum Bartender
 
Unnikrishnan Nair
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

This codelet will work

When you want to put something on session, use this code in your servlets

HttpSession session = request.getSession();
session.setAttribute("key", value);

and when you want to retrieve, use this

HttpSession session = request.getSession();
Object obj = session.getAttribute("key");

Now type cast that to your real object.

If the code is in JSP, you have a readily available session object, and you dont have to create one using request.getSession(). Rest is the same

Regards
Unnikrishnan Nair
 
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
you dont have to create one using request.getSession()


Clarification: the getSession() method doesn't generally create a session. A new session will only be created if one does not already exist. And usually, by the time your code gets to anywhere where you can make this call, a session will already have been created on your behalf.
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!