CodyBugstein
CodyBugstein

Reputation: 23322

Keep a Java object alive for the duration of a session

In my JSP application, I want to keep track of the user that's logged in.

When the user tries to log in, I use database transactions in a UserManager class to verify that the entry exists (I'm not aiming to make a very secure site, most of this is for learning).

That UserManager class constructs a User instance object out of the retrieved information on the user (i.e. their name, age, photo, etc).

I use this object to efficiently call prepare the presentation on the user's home page, after the log in is successful.

The trouble is, I don't know how to keep this User object alive for the duration of the whole session with the user. For example, if he goes to other pages, I still want to be able to call

user.getPhoto()

or

user.getLastName()

without complicated database queries each time.

Is there any way to do this?

Upvotes: 1

Views: 1164

Answers (1)

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85779

Store the object in session. Inside your servlet, just call this:

User user = ... //use your UserManager or something else to get the user
if (<valid user>) {
    //store the user object in session
    request.getSession().setAttribute("user", user);
}
//forward to the next view...

Then you can retrieve the data in your view (JSP, Facelets) using Expression Language:

<!DOCTYPE html>
<html lang="en">
    <!-- tags... -->
    <div>
        Welcome ${user.name}
        <!-- ${user.name} will call session.getAttribute("user").getName() for you -->
    </div>
</html>

More info:

Didn't provide an example using scriptlets because you should not use them. Explanation on link above.


Don't forget to clear the session when performing a log out:

request.getSession().invalidate();

Upvotes: 4

Related Questions