如何在HttpSession中存储Java对象? [英] How do you store Java objects in HttpSession?

查看:115
本文介绍了如何在HttpSession中存储Java对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以当我请求这个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不为空?

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);

在Servlets中,您有4个可以存储数据的范围。

In Servlets you have 4 scopes where you can store data.


  1. 申请

  2. 会话

  3. 申请

  4. 页面

  1. Application
  2. Session
  3. Request
  4. Page

确保您理解这些。有关更多信息,请参阅此处

Make sure you understand these. For more look here

这篇关于如何在HttpSession中存储Java对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆