Jens D
Jens D

Reputation: 4676

Correct semantics for updating session data

What is the correct way to update objects held in my session? Must I always call setAttribute() on objects, retrieved from the session, which have had their state changed? I'm only referring here to session attributes which have already been created and stored in the session - not new attributes.

Let's say I have a Person object stored in my session and each request does:

Person p = (Person) session.getAttribute("person");

Then the object referenced by 'p' is always going to be the same object returned to you across requests. The container (at least Tomcat) isn't going to give you a new copy every time. The point here is that if you subsequently do p.setName("Joe the Plumber") and don't call setAttribute("person", p), the object held in the session is still going to be updated and you will see the updates across requests.

However, once clustering and thus session replication come into play, you typically always have to call setAttribute() so that the clustering code is able to know when to distribute your updated session object. I do realize that some containers have other mechanisms to achieve this without calling setAttribute().

Is this a gray area of the Servlet spec?

Upvotes: 1

Views: 123

Answers (2)

Mark Thomas
Mark Thomas

Reputation: 16615

Yes, it is a grey area. The J2EE specifications in general do not discuss the expected behaviour when using clustering.

There is an enhancement request open against the Servlet specification: https://java.net/jira/browse/SERVLET_SPEC-1

Please feel free to add your views on what, if anything, should be added to the spec in that issue.

Upvotes: 1

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85779

Is this a gray area of the Servlet spec?

No it is not. When you retrieve a non-immutable object and modify its state, the changes will be reflected wherever the object can be referenced, in this case, in the internal Map<String, Object> held in session.

When you use clustering, you will need to explicitly call to HttpSession#setAttribute to notify the server you're updating the session variable, in order that the session variable be updated in the other clusters.

Upvotes: 1

Related Questions