Question:
I’m developing some applications with servlets. I’ve been declaring static variables to preserve state, but when two instances of the servlet run at the same time, the second instance overwrites the values of the first instance. What can I do?
Answer:
Rather than preserve state with static variables, you should associate state with sessions. There may be multiple instances of a servlet running in a servlet engine and each instance may be serving requests from multiple clients.
Requests from different clients will cause different state changes. If you store states in static variables, other instances of the servlet may overwrite the values and so may requests from different clients.
To preserve state on a session basis, obtain the HttpSession associated with a client request using
HttpRequest.getSession()
You can associate values with the session by storing them in the session object with
setAttribute(String name, Object value)
By storing values in a session, you can preserve state on a per client basis.
Object myValue;HttpSession session;myValue = "some value";session = request.getSession();session.setAttribute("my.attribute", myValue);