Alex Dowining
Alex Dowining

Reputation: 970

Set/Get Objects from HttpSessions (Java)

I set an object into an HttpSession. This object is an instance of class User. Then, in another class I'm trying to do something like this:

User user = session.getAttribute("userObject");

I read about Serializable but I can't understand how it works. Is there a direct and easier way to do this?

Upvotes: 0

Views: 404

Answers (4)

Matt
Matt

Reputation: 11805

Serializable is only really important here if you're trying to run in a clustered session environment. If so, the app container (tomcat or otherwise) will need to transform all of the objects in your session into byte data that it can stream to the other servers in order to replicate the session. In this case, all your session values need to implement Serializable and contain only properties which themselves implement Serializable.

Upvotes: 0

Bozho
Bozho

Reputation: 597362

Imagine the session as a simple, type-unsafe Map. You can put anything in it, and you can take it out, provided you know the type you expect. So, if you have put a User object, then use:

User user = (User) session.getAttribute("userObject");

If you have put a Long (the userId)

Long id = (Long) session.getAttribute("userObject");
User user = getUserById(id);

Upvotes: 4

tjg184
tjg184

Reputation: 4686

Read this on serialization:

Why and how is serialization used in Java web applications?

We are assuming you're doing this somewhere else.

session.setAttribute("userObject", user);  

Upvotes: 1

Guido
Guido

Reputation: 47685

Your code seems ok, you only need a cast:

User user = (User) session.getAttribute("userObject");

Upvotes: 1

Related Questions