0

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?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Alex Dowining
  • 980
  • 4
  • 19
  • 41

4 Answers4

4

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);
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
1

Your code seems ok, you only need a cast:

User user = (User) session.getAttribute("userObject");
Guido
  • 46,642
  • 28
  • 120
  • 174
  • I tried this before but i'm taking a java.lang.ClassCastException – Alex Dowining Jul 04 '12 at 21:08
  • I would verify the User object you casted with is the right type. Check the import. Also, verify you are putting the right type provided session.setAttribute. – tjg184 Jul 04 '12 at 21:10
1

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);  
Community
  • 1
  • 1
tjg184
  • 4,508
  • 1
  • 27
  • 54
0

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.

Matt
  • 11,523
  • 2
  • 23
  • 33