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.
A stack and a heap are used for memory allocation in Java. However, the stack is used for primitive data types, temporary variables, object addresses etc. The heap is used for storing objects in memory.
In Java an HttpSession is established when the first request reaches your application. The Servlet Spec implementation in your container (Jetty, Tomcat, WebSphere, etc) will create and manage the HttpSession. The browser will receive a JSESSIONID cookie which will identify this particular session in the future.
The HttpServletRequest interface provides two methods to get the object of HttpSession: public HttpSession getSession():Returns the current session associated with this request, or if the request does not have a session, creates one.
The HttpSession is provided by the servlet container to give a way to store objects for a given user based on a cookie provided in the user's request.
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
Add it to the session, not to the request.
HttpSession session = request.getSession(); session.setAttribute("object", object);
Also, don't use scriptlets in the JSP. Use EL instead; to access object
all you need is ${object}
.
A primary feature of JSP technology version 2.0 is its support for an expression language (EL). An expression language makes it possible to easily access application data stored in JavaBeans components. For example, the JSP expression language allows a page author to access a bean using simple syntax such as
${name}
for a simple variable or${name.foo.bar}
for a nested property.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With