Java HttpSession .getAttribute(字符串名称)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38646360/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 03:37:15  来源:igfitidea点击:

Java HttpSession .getAttribute(String name)

javajakarta-eehttpsessiongetattribute

提问by Display Name

I have a simple, short question but not found the answer anywhere. I created an HttpSession and want to get an attribute from it, for example a User object.

我有一个简单而简短的问题,但在任何地方都找不到答案。我创建了一个 HttpSession 并想从中获取一个属性,例如一个 User 对象。

HttpSession session = request.getSession(true);
Object userObject = session.getAttribute("name");
if ((userObject != null) && (userObject instanceof User)) {
    User currentUser = (User) userObject;
    ...
}

The question is the following: .getAttribute function gets a String name as parameter - what is the name? From where do I know the name? Is it predefined somewhere? - then where to define another one?

问题如下: .getAttribute 函数获取一个字符串名称作为参数 - 名称是什么?我从哪里知道名字的?它是在某处预定义的吗?- 那么在哪里定义另一个?

Thank you!

谢谢!

回答by LeHill

Usually, you add attributes to the session yourself like so:

通常,您自己向会话添加属性,如下所示:

User someObject = new User();
session.setAttribute("pickaName", someObject);

Then you can get the session and pull off this attribute using that same name you used earlier like so:

然后您可以获取会话并使用您之前使用的相同名称取消此属性,如下所示:

User sameObject = (User) session.getAttribute("pickaName");

回答by Julian

.getAttribute function gets a String name as parameter - what is the name?

.getAttribute 函数获取一个字符串名称作为参数 - 名称是什么?

If you want to get attributes from Session, you need to set them to the Session before like so:

如果你想从 Session 获取属性,你需要像这样将它们设置到 Session 之前:

User aux = new User();
HttpSession session = new HttpSession();
session.setAttribute("myUserObject", aux);
User user = (User) session.getAttribute("myUserObject");