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.
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.
Make sure you understand these. For more look here