How do you store Java objects in HttpSession?

Tamer picture Tamer · Apr 23, 2011 · Viewed 181.5k times · Source

So I am trying to get a servlet to add a Java object to the session of the user, when this servlet is requested. But after the servlet redirects to the next page and I try to retrieve the object, I get a null object instead.

Here is what I do to add the object to the HttpSession (in the servlet):

request.setAttribute("object", obj);

Then I try to retrieve it by (in the JSP):

 Object obj = request.getAttribute("object");

So how would I get obj to not be null?

Update: I have also tried this with nothing:

HttpSession session = request.getSession();
session.setAttribute("object", obj);

with the following in the JSP:

 Object obj = request.getSession().getAttribute("object");

Both ways still return null.

Answer

Romain Hippeau picture Romain Hippeau · Apr 23, 2011

You are not adding the object to the session, instead you are adding it to the request.
What you need is:

HttpSession session = request.getSession();
session.setAttribute("MySessionVariable", param);

In Servlets you have 4 scopes where you can store data.

  1. Application
  2. Session
  3. Request
  4. Page

Make sure you understand these. For more look here