File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Servlets and the fly likes Session variables in JSP Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Servlets
Bookmark "Session variables in JSP" Watch "Session variables in JSP" New topic

Session variables in JSP

Lisa Strite

Joined: Dec 19, 2000
Posts: 4
I have an html page with a form that POSTs to a servlet. The servlet then creates some objects does some work and calls a JSP page. The JSP page displays the information along with another form. Some of the information it displays is session variables I set in the servlet.
For example, I have this line of code in my servlet:
session.putValue("imageNamePath", bean.getImageNamePath());
Now, I would also like to put some complicated objects in session variables. I would like them to persist for the whole session. Basically the user sets up the initial parameters on the first page, then as they go through their session, they are making modifications to the object.
However, when it gets into the servlet the second time (this time they are making modifications to the existig object), I can't access the object. I try the following:
TSPBean bean =(TSPBean)session.getValue("tspBean");
and I get null. I have previously saved this in the session (the first time the servlet was called) using:
session.putValue("tspBean", bean);
Does anyone have an idea of what I'm doing wrong? Are there only certain types of objects you can store in a session variable, like do they have to be serializable or anything like that?
William Brogden
Author and all-around good cowpoke

Joined: Mar 22, 2000
Posts: 13037
You can store any object reference in a session. They need to be serializable if you are going to use capabilities such as load sharing, but thats the only reason.
First thing to check is to see if you are in fact getting back the same session. Try printing the String returned by the getId() method from the session. Another handy method is getAttributeNames which returns an Enumeration over all of the object names.

author of:
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
If you are using Tomcat, there is a bug in some versions that produce the behavior you are seeing. Basically, after you establish your session (req.getSession(true) ;), you should flush the buffer (res.flushBuffer() ;). This will make sure the session cookie in the header gets written out before you do the forward.
Hope this helps.
[This message has been edited by Jim Seach (edited December 19, 2000).]
I agree. Here's the link:
subject: Session variables in JSP
jQuery in Action, 3rd edition