Java HttpSession setattribute throws non-serializable exception on qa, but not in local environment

StackOverflow https://stackoverflow.com/questions/3460249

Question

The object I'm saving to the session is a LocalizationContext, which is not serializable, and my Tomcat is 5.5.28, while the qa server is Tomcat 5.5.30. This is from the Tomcat docs:

Whenever Catalina is shut down normally and restarted, or when an application reload is triggered, the standard Manager implementation will attempt to serialize all currently active sessions to a disk file located via the pathname attribute. All such saved sessions will then be deserialized and activated (assuming they have not expired in the mean time) when the application reload is completed.

In order to successfully restore the state of session attributes, all such attributes MUST implement the java.io.Serializable interface. You MAY cause the Manager to enforce this restriction by including the <distributable> element in your web application deployment descriptor (/WEB-INF/web.xml).

This makes me think it should be breaking on my local as well, and that you can never save a session attribute in Tomcat unless it implements Serializable.

EDIT:

Sorry, to be more clear, my question is two-fold. Do all session attributes have to be serializable, and if they do, why might it still work on my local environment?

Was it helpful?

Solution

It is preferable that session attributes (and hence sessions) are serializable, especially when developing for environments where user sessions can be persisted only to be restored later. This is more or less a pre-requisite for failover/migration of sessions in a cluster.

But clustering is not the only scenario where sessions will be serialized. In a single container, sessions can be persisted when the container is being shutdown, and will be de-serialized when the container is brought back again. This of course, depends on the container support, and a lot of containers including Tomcat support this feature.

The rational answer on why the error does not manifest in the local environment is that the error is flagged only when there is an attempt to serialize the session. The container does not include checks on whether the attribute values in the session, on whether they are serializable or not. Containers wouldn't implement this check; after all, such a test would include actual serialization of the session, which can be performance intensive, with the only benefit of being defensive against programming mistakes.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top