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.
Here you can do it by using
HttpRequest
orHttpSession
. And think your problem is within the JSP.If you are going to use the inside servlet do following,
or
and after setting your attribute by using request or session, use following to access it in the JSP,
or
So seems your problem is in the JSP.
If you want use scriptlets it should be as follows,
Or can use expressions as follows,
or can use EL as follows,
${object}
or${sessionScope.object}
You are not adding the object to the session, instead you are adding it to the request.
What you need is:
In Servlets you have 4 scopes where you can store data.
Make sure you understand these. For more look here
The request object is not the session.
You want to use the session object to store. The session is added to the request and is were you want to persist data across requests. The session can be obtained from
Then you can use setAttribute or getAttribute on the session.
A more up to date tutorial on jsp sessions is: http://courses.coreservlets.com/Course-Materials/pdf/csajsp2/08-Session-Tracking.pdf
Add it to the session, not to the request.
Also, don't use scriptlets in the JSP. Use EL instead; to access
object
all you need is${object}
.