Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
6.2k views
in Technique[技术] by (71.8m points)

jsp - How do you store Java objects in HttpSession?

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.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...