如何在 HttpSession 中存储 Java 对象? [英] How do you store Java objects in HttpSession?
问题描述
因此,当请求此 servlet 时,我试图获取一个 servlet 以将 Java 对象添加到用户的会话中.但是在 servlet 重定向到下一个页面并且我尝试检索该对象之后,我得到了一个 null
对象.
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.
这是我将对象添加到 HttpSession(在 servlet 中)的操作:
Here is what I do to add the object to the HttpSession (in the servlet):
request.setAttribute("object", obj);
然后我尝试通过(在 JSP 中)检索它:
Then I try to retrieve it by (in the JSP):
Object obj = request.getAttribute("object");
那么如何让 obj 不为 null?
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);
在 JSP 中具有以下内容:
with the following in the JSP:
Object obj = request.getSession().getAttribute("object");
两种方式都返回null.
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);
在 Servlet 中,您有 4 个范围可以存储数据.
In Servlets you have 4 scopes where you can store data.
- 申请
- 会话
- 请求
- 页面
确保你理解这些.如需更多信息,请查看此处
Make sure you understand these. For more look here
这篇关于如何在 HttpSession 中存储 Java 对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!