Search code examples
javaservletscastinghttpsession

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?


Solution

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