Java HttpSession .getAttribute(String name)
Asked Answered
J

2

6

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 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?

Thank you!

Joellajoelle answered 28/7, 2016 at 20:42 Comment(0)
V
10

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");
Vasectomy answered 28/7, 2016 at 20:48 Comment(3)
Thank you, I think I got it. If I'm right, if I want to get for example a User object with getAttribute in a session, I have to create for example a login method, where I set the attribute for the user, am I?Joellajoelle
Exactly. Create the object and add it first, then you can retrieve it later.Vasectomy
Thank you, it helped me a lot!Joellajoelle
A
0

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

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

User aux = new User();
HttpSession session = new HttpSession();
session.setAttribute("myUserObject", aux);
User user = (User) session.getAttribute("myUserObject");
Ap answered 28/7, 2016 at 21:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.