为什么关键字“瞬态”对Java中的Servlet HTTPSession没有影响?(Why does keyword “transient” has no effect for Servlet HTTPSession in Java?)

瞬态关键字究竟意味着什么? 我有一个Class属性标记为transient:

public class NodeClassifier { private transient HashMap<String, Node> nodeCache = new HashMap<>(); ... }

在将一个NodeClassifier对象存储并恢复到HttpSession之后,该属性仍然具有前一个Session的值。

它不应该是空的吗?

环境是在Glassfish4上运行的普通Servlet。

What does the transient Keyword exactly mean? I have a Class attribute marked as transient:

public class NodeClassifier { private transient HashMap<String, Node> nodeCache = new HashMap<>(); ... }

After storing and recovering an NodeClassifier Object into the HttpSession the Attribute still has the Value from previous Session.

Shouldn't it be empty?

The Environment is a plain Servlet running on Glassfish4.

最满意答案

transient意味着当对象被写为字节时,该值不会被序列化(使用默认的Java对象序列化)。

会话的序列化可能会也可能不会发生(只需要在进程之间传递会话,或者将其持久化到磁盘,但通常不需要在单个JVM servlet容器中,只能将它们保存在内存中),所以你应该不依赖于那种“迷失”的价值观。

如果你不想在会议中存活,不要放在那里。 考虑使用请求属性。

transient means that the value will not be serialized (using default Java object serialization), when the object is written out as bytes.

Serialization of a session may or may not happen (it is only needed to pass the session between processes, or to persist it to disk, but usually not needed in a single JVM servlet container that can just keep them in memory), so you should not rely on values being "lost" that way.

If you don't want stuff to survive in the session, don't put it there. Consider using request attributes instead.

更多推荐