Madz
Madz

Reputation: 199

Java Class using a static String variable

I am a little confused here, building a web application which has tab sheet. In in the tab sheet class I am using a data member - static String variable to store the tab selected by the user. I am doing this so that I can display the tab last selected by the user when ther user returns to the tab sheet. I am getting the desirable results. However, if I logout and login (after deleting the cache on browser), the tab sheet is still picking the tab which user had last selected and not picking the default tab. The tab sheet is being initialised by another component. What I dont understand is, does the class defination not garbage collected? why is it picking the old data? how to fix this?

Upvotes: 0

Views: 441

Answers (4)

danp
danp

Reputation: 15241

It's not static if the value is constantly changing. I think you should look at using a different mechanism to store these kinds of variables.

Upvotes: 0

Attila
Attila

Reputation: 28762

Just because you clear the browser cache, it does not affect the object on the server, where your static variable is stored. You need to explicitly re-set it if the user logs out (or logs in, your choice)

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500225

You seem to be assuming that making a variable static somehow corresponds to isolating it to a user session. It doesn't.

If you want any sort of session handling, you'll have to actually have a session. (You'll need to consider what happens across server restarts, multiple servers etc.)

When you have a static variable, that's one variable for that class in that classloader. It doesn't have anything to do with the user. All users will see the same variable, if they hit the same server.

You haven't told us anything about what technologies you're using to build your web app, but basically you should look into what's provided for you in terms of server-side user sessions - or propagate the information using hidden fields or something similar, so the server doesn't need to keep track of it at all.

Upvotes: 2

esaj
esaj

Reputation: 16035

Static members are stored per-class, not per-object, so the value of the static member is the same across all class instances (objects), and does not get "reset" when the instance goes out of scope. Using static member this way is a bad idea, because all the users of your application will see the same value, and if one of them causes it to change, the changed value will be visible to everyone (ie. if user 1 changes the tab, the tab would change for all other users also).

Upvotes: 1

Related Questions